Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Not Recognizing Classes Added to Page Dynamically

I am working on a project, where I'd like to add many elements of the same class to a page, and make all of these classes accessible to a $('selector').click(); event handler. What is happening though, is none of the dynamically added elements of the same class are responding to clicks.

To give you a better picture of what I mean, I made up a sample jsFiddle, which is very similar to the actual problem in my project:

Link to jsFiddle: http://jsfiddle.net/8LATf/3/

  • One element of the class "added_element" is on the page already when it loads. This element is clickable.

  • A button is clicked, and it adds other elements of class "added_element" to the page dynamically using append. None of these elements are clickable.

How can I make all of the elements of class "added_element" clickable? I'm guessing it has to do with the selector I use in the event handler, but I haven't been able to figure it out.

Any help is much appreciated!!!

like image 703
Camden Reslink Avatar asked Jun 25 '12 14:06

Camden Reslink


1 Answers

You need to delegate your handler. The easiest way is to delegate everything to the document using .on('click', ...) (this is how .live() is converted internally, as of jQuery 1.7):

$(document).on('click','.added_element',function() {
    var id = $(this).attr('id');
    alert(id);    
});

​http://jsfiddle.net/mblase75/8LATf/4/

However, in your case, you can delegate to the #container, since all the added elements appear within that. Delegating to the closest possible DOM element is preferable for efficiency reasons, when it's possible.

$('#container').on('click','.added_element',function() {
    var id = $(this).attr('id');
    alert(id);    
});

​ ​http://jsfiddle.net/mblase75/8LATf/5/

like image 126
Blazemonger Avatar answered Dec 17 '22 14:12

Blazemonger