Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click() jquery function not available on new divs

During the running of my website i create new divs using jquery with class "a". I have defined a click() function for "a" class as follows:

$(document).ready(function() {
    $(".a").click(function(){
        $(".a").hide();
    });
});

Problem is that the new divs created with the same class do not call this function when clicked. Other divs with "a" class which are there at the beginning do. What am I doing wrong?

like image 747
Nachshon Schwartz Avatar asked May 31 '11 19:05

Nachshon Schwartz


3 Answers

$(document).delegate('.a', 'click', function() {
  $(this).hide();
});
like image 67
John Strickler Avatar answered Sep 30 '22 06:09

John Strickler


Try using the .live() function which should also apply for newly inserted DOM elements that match your selector:

$(document).ready(function() {
    $(".a").live('click', function(){
        $(".a").hide();
    });
});
like image 41
Darin Dimitrov Avatar answered Sep 30 '22 08:09

Darin Dimitrov


This might also work.

(function($) {  
  $(document).ready(function () {
    $('body').on('click', '.a', function() {
      $(this).hide();
    });
  });
}( jQuery ));

.on() attaches events to controls that are both present and not yet present.

like image 22
Steve Hanson Avatar answered Sep 30 '22 06:09

Steve Hanson