Maarten Wolfsen Maarten Wolfsen - 2 months ago 7
CSS Question

jQuery adding with ++ multiplies after using function again

I made a function called test (for example), and it works like this:

function test(){
var i = 0;

$('.container').click(function(){
$(this).append('<div class="element"></div>');
$('.element').click(function(){
if (i >= 10){
$('this').remove();
} else {
i++;
}
});
});
};
test();


When I click the class
.container
, a div appends with the classname
.element
. When I click this div, var
i
goes up, until reaching 10. Then the div called
.element
is removed.

The problem is, is when I click
.container
again, after
.element
is removed, the
i
variable is acting like its clicked twice. After that trice, and so on. How do I counteract this?

Answer

You need to attach event to dynamically added elements using .on()

$('.container').click(function(){
        $(this).append('<div class="element"></div>');

    });

 $('body').on('click','.element',function(){
   if (i >= 10){
      $(this).remove();
   } else {
         i++;
   }
});

Also remove .element div event handler inside .container div

Comments