0

I have content that I'm loading using an AJAX call and displaying the HTML (consisting of divs, etc) inside of a ul parent.

Now I've written a series of .click and .hover functions that work perfectly on everything, right up to where my content is dynamically loaded, and then don't work at all on the dynamically-loaded content.

I've gone through all my div ids to make sure they are correct and they are. Is there a way to gain control over the AJAX-loaded material?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Mark
  • 3,653
  • 10
  • 30
  • 62

4 Answers4

0

Your event handlers are bound to elements that exist at the time that they are set.

Either re-attach the handlers to the new, dynamically-created material, or make use of live or delegate; these "attach a handler to the event for all elements which match the current selector, now and in the future".

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

The problem is that your code run only with the elements that existed at that time and no the "future" elements. You have 2 choices:

1) Re-run your "onload" javascript code (that was applied on document ready) after you load your ajax content.

2) Use .live() instead of .bind(): So change

$('#selector').bind('click', function(){..

To

$('#selector').live('click',function(){..

The difference is that live uses the elements that match the selector now and in the future, versus bind uses the elements that match the selector only at the time it's called.

Hope this helps. Cheers

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
-1

You should either rebind the events after the content is loaded or use

.delegate (api) to have the event attached automatically to newly loaded elements.

something like:

$("ul#container").delegate("li", "hover", function(){
    doStuff();
});
$("ul#container").delegate("li", "click", function(){
    doOtherStuff();
});
Variant
  • 17,279
  • 4
  • 40
  • 65
-1

Change

$('a#whatever').click(function(){....

To

$('a#whatever').live('click',function(){....
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145