5

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?

Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98

4 Answers4

4
$(document).delegate('.a', 'click', function() {
  $(this).hide();
});
John Strickler
  • 25,151
  • 4
  • 52
  • 68
  • 1
    +1 for using `delegate()` instead of `live()`, even though in this instance they hardly differ. – Levi Morrison May 31 '11 at 22:06
  • 1
    It's important to note that the selector you call `.delegate` from should be as close to one you want to delegate to as possible. – Levi Morrison Jun 06 '11 at 16:12
  • +1 And that it itself is not a dynamic element that comes after the call. Make sure its static on the page or is bound after it is appended. – John Strickler Jun 06 '11 at 17:00
3

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();
    });
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    Please do not support the use of `live()`. It was an unfortunate mistake. Please use `delegate()` instead; -1 – Levi Morrison May 31 '11 at 19:29
  • This sent me a-Googling, which turned up this question and answer on why `delegate()` can be better than `live()`: http://stackoverflow.com/questions/4204316/jquery-live-vs-delegate – marramgrass May 31 '11 at 19:40
2

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.

-1

Use the "live" method.

http://api.jquery.com/live/

Joe Enzminger
  • 11,110
  • 3
  • 50
  • 75