Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery with elements generated dynamically

I've been working with jQuery for a pair of weeks and I've noticed it works fine with objects that are in the original HTML document, but when I generate a new element using jQuery the library doesn't get any of its events.

Let's say I try to run something like this:

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

If the HTML does have something like this:

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

Then clicking on the word Whatever gets me a nice alert.

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

Is there a way to make jQuery work with those elements, somehow?

like image 536
PixelRobot Avatar asked Dec 03 '22 08:12

PixelRobot


1 Answers

Thats because the : (corrected)

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

Means, in literal terms:

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

so naturally, adding a new DOM element wont automagically apply the click.

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

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

Warning on simply rebinding everything

If done wrong, it can lead to undesired effects, ie, making the number of times the event triggers something increase. To stop this, you may need to first unbind them to delete the previous passes binds.

ie,

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

so to stop this, you need

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

in the rebind.

like image 103
Kent Fredric Avatar answered Dec 23 '22 03:12

Kent Fredric