Duplication of jQuery event

Asked

Viewed 59 times

1

Test scenario

index

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <title></title>
    <script type="text/javascript">

        function carregar() {
            $.ajax({
                url: 'inc.php',
                success:function(response){
                    $('#ret').html(response).show();
                },
                error:function(xhr, ajaxOptions, thrownError){
                    console.log(thrownError);
                }
            });
        }
    </script>
</head>
<body>
    <div>
        <button onclick="carregar()">Carregar</button>
    </div>
    <hr>
    <div id="ret"></div>
</body>
</html>

inc.php

<script type="text/javascript">

    $(document).keydown(function (e) {
        if (e.altKey && e.keyCode == 67) {   
            clone();
        }
    });

    function clone() {
        const template = $('#elementos > #el').last();
        const novo = template.clone();
        $('#elementos').append(novo);
    }
</script>
<div>
    <button onclick="clone()">Clonar</button>
    <div id="elementos">
        <p id="el">Elemento</p>
    </div>
</div>

Simulation

The index, has a button that calls Ajax the content of inc.php, where it has a function that clones the element with id="el" the "clone" button or the "Alt+C" key shortcut".

What happens is that each time you "reload" the content of inc.php by the "press" button of index, it adds +1 clone only by shortcut, but not by button, as below:

bug


Doubt

  • Why this happens only with the "shortcut" set?
  • 1. Whenever the event keydown is used in jQuery, it is added (and not replaced). That is, every time the page inc.php is loaded, a new action will be added in the above mentioned event. 2. This does not occur with the "clone" button, because the function onclick will always have only one command and the function will be replaced. I do not know if I understand (anything mount a gif).

  • I believe you reversed the text (the title is ok): who duplicates the shortcut and not the :D button

  • 1

    @Sam true! Thanks!! Kkk

1 answer

2


This happens because each time you load, a new one is created Event Listener $(document).keydown in memory, and accumulates. In the case of the button this does not occur because it calls a function that does not duplicate in loading.

What you have to do is stop $(document).keydown is executed at each load, that is, it enters only 1 time in memory.

A suggestion is to create a variable (called flag) initially false and put the $(document).keydown within a if and change the value of the variable to true. Thus, the stretch within the if will only be executed the first time, avoiding duplicating the $(document).keydown:

var flag;

if(!flag){      
   flag = true;
   $(document).keydown(function (e) {
      if (e.altKey && e.keyCode == 67) {   
         clone();
      }
   });
}

function clone() {
   const template = $('#elementos > #el').last();
   const novo = template.clone();
   $('#elementos').append(novo);
}
  • You can try it. It’ll work like a glove. ;?)

  • 100%! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.