IberoMedia
IberoMedia

Reputation: 2304

jQuery how do I interact with ajax loaded content?

I am successfully loading content through the use of

jQuery(".menu li a").click( function(event){

    jQuery("#loadingArea").load(this.href)

});

After the content is loaded, I have new elements in my page. I have tried to apply jQuery manipulation (do something when I click or hover the mouse), and the element does not respond.

Please explain to me why I am unable to trigger events in content that has been loaded through ajax?

Does the method .load() has something to do with this (i.e. if I had used $.ajax I would be able to interact with such content)?

Thank you,

Upvotes: 2

Views: 1812

Answers (6)

Valentin E
Valentin E

Reputation: 1413

.live() is now removed

That's the way to do it now :

$(document).on("click",".menu li a",function(e){

});

Upvotes: 2

beardhatcode
beardhatcode

Reputation: 4753

.live() or .delegate() will help you here. becouse the new elemnts are not there on startup, the moment you bind the functions the will not be applied. By uing live() the event bubbles up and you can bind an event to it

Upvotes: 0

Seth
Seth

Reputation: 6260

jQuery(".menu li a").click( function(event){

    jQuery("#loadingArea").load(this.href);

});

jQuery("#loadingArea a").live('click', function() {

    /* Insert eMagic! */

});

Upvotes: 3

Headshota
Headshota

Reputation: 21449

you should use live event handlers for ajax loaded content

$("a").live("click",function(){
// your code
});

live binds events to future elements as well as existing ones.

Upvotes: 0

rolling stone
rolling stone

Reputation: 13016

.live() is the answer to your problem:

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

From the docs:

The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.

Upvotes: 0

genesis
genesis

Reputation: 50966

You'll have to use .live() or .delegate()

so ajax-loaded content is delegated, too

Upvotes: 2

Related Questions