-6

please help me out with this issue: both .click and .on are not working when i am clicking on appended

$(document).ready(function() {
    $( ".cooldiv" ).click(function() {
      alert(1);
    });

    $(".cooldiv").on('click',  function(){
      alert(1);
    });

    $("#fields_count").change(function() {
                var $newDiv = $('<div class="cooldiv">i am cooldiv</div>');
                //$($newDiv).addClass('cooldiv');
                $("#testdivs").append($newDiv);
    });
});

html is:

<div id="testdivs"><div class='cooldiv'>qwdqwdwef</div></div>
<input type="text" size="3" id="fields_count" name="fields_count" value="3">

when i am clicking on a div containing 'qwdqwdwef', alert comes, but it does not when clicking on appended div's of the same class. Any ideas?

user3610593
  • 17
  • 1
  • 1

3 Answers3

4

Try to use event-delegation, you may ask why should i use delegation here..? The answer is while binding events to the element with the class .cooldiv, it would not be available in the Dom. so event wont get bound to that. So we have to bye pass the situation by means of event delegation

$('#testdivs').on('click','.cooldiv',function(){
 alert(1);
});
Rajaprabhu Aravindasamy
  • 63,064
  • 13
  • 90
  • 119
3

You need to use delegation. Because your new element was not there when you added the click event handler you need to use a delegated event handler.

Try this instead:

$(document).on('click',  '.cooldiv', function(){
  alert(1);
});

You might want to check out the jQuery documentation about .on().

Sergio
  • 27,160
  • 10
  • 79
  • 126
2

You need event delegation.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

try this:

  $("#testdivs").on('click','.cooldiv',  function(){
   alert(1);
  });
Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114