JQuery with dynamically generated elements

I have been working with jQuery for a couple of weeks, and I noticed that it works great with objects that are in the original HTML document, but when I create a new element using jQuery, the library does not receive any of its events.

Let's say I'm trying to run something like this:

$('.whatever').click(function() { alert("ALERT!"); }); 

If HTML has something like this:

 <span class="whatever">Whatever</span> 

Then clicking on the word Whatever gets a good warning.

But if the span element is added dynamically using jQuery, nothing happens when you click on it.

Is there a way to get jQuery to work with these elements, somehow?

+4
source share
6 answers

This is because: <Sub> (adjusted) sub>

 $('.whatever').click(function() { alert("ALERT!"); }); 

So literally:

  Find all elements currently on the page that have the class ".whatever"
 Foreach element in that result set, bind this function to its click event

Naturally, adding a new DOM element will not be automatically applied by click.

the best way to solve this is to create bindings during the insert phase, that is:

  var x = document.createElement("span"); $(x).click(function(){ }); //etc $(somcontiner).append(x); 

A warning about simple recovery of everything

If everything is done incorrectly, this can lead to undesirable effects, i.e. the number of times the event triggers something. To stop this, you may need to unlock them first to remove previous bindings.

those.

 $(x).click(foo); $(x).click(bar); //foo and bar should both execute. 

to stop it you need

 $(x).unbind("click"); $(x).click(foo); 

in repeated order.

+9
source

If you have jQuery 1.3 or later, try using live to add events to dynamically generated elements:

 $('.whatever').live("click", function() { alert("ALERT!"); }); 
+6
source

Thanks to everyone.

Somehow I thought that the elements were added to the DOM automatically by jQuery, just adding them anywhere.

I also found additional information on the topic:

http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F

http://learningjquery.com/2008/03/working-with-events-part-1

http://learningjquery.com/2008/05/working-with-events-part-2

Just in case someone needs it.

+3
source

You need to re-confirm it.

 function bindme(){ $('.whatever').click(function(){ alert('binded'); }); }; bindme(); //function that will generate something function foo(){ $('.whatever').val('oryt'); bindme();//rebind itagain } 
0
source

Also check out reglib , a similar library that lets you search for the programming style you are looking for.

0
source

In addition, there is a great jQuery plugin that takes care of this, called livequery

0
source

All Articles