kylemac
kylemac

Reputation: 623

How to use jQuery .live() with ajax

Currently I am using John Resig's LiveQuery plugin/function to allow users to sort through a long unordered-list of list-items. The code is as follows: $('input#q').liveUpdate('ul#teams').focus(); The issue arises when I use ajaxified tabs to sort the lists. Essentially I use ajax to pull in different lists and the liveUpdate() function doesn't have access to the new li's.

I assume I would need to bind this using the .live() function. But I am unclear how to bind this to an ajax event, I've only used the "click" event. How would I bind the new liveUpdate() to the newly loaded list-items?

EDIT: The ajax tabs is run through the wordpress ajax api so the code is fairly complex, but simplified it is something like this:

$('div.item-list-tabs').click( function(event) {
    var target = $(event.target).parent();

    var data = {action, scope, pagination}; // Passes action to WP that loads my tab data
    $.post( ajaxurl, data, function(response) {
        $(target).fadeOut( 100, function() {
            $(this).html(response);
            $(this).fadeIn(100);
        });
     });

     return false;
});

This is simplified for the sake of this conversation, but basically once the $.post loads the response in place .liveUpdate() doesn't have access to it. I believe the .live() function is the answer to this problem, I'm just unclear on how to implement it with the $.post()

Upvotes: 7

Views: 10869

Answers (5)

Prajith
Prajith

Reputation: 11

I also got trouble with using just

$('selector').click(function(.. 

after an Ajax call, and finally found that we need to use

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

or the new method

$(document).on('click', 'selector', function(){..

to bind the event for new elements created after an Ajax call.

$(document).on('click','selector', function(event){
//your code    
});

For live

$('selector').live('click', function(event){    
//your code    
});

Upvotes: 1

maniak
maniak

Reputation: 462

As mentionned in the documentation of JQuery, .live() is considered deprecated. You should use the method .on() instead.

$("#yourSelector").on("click", function() {
    // statement
});

To also manage futur object of the selector type, you can use .on() like this

$(document).on("click", "#yourSelector", function() {
    // statement
});

Upvotes: 4

relu
relu

Reputation: 158

Try using jQuery's Ajax Events

$('input#q').ajaxComplete(function(){
    $(this).liveUpdate('ul#teams').focus();

    $(this).unbind('ajaxStop');
});

Upvotes: 1

Sunil Raj
Sunil Raj

Reputation: 460

$("div.item-list-tabs").live("click",function(){
//statements..
});

Upvotes: 0

Puaka
Puaka

Reputation: 1751

$('input#q').live(function() {
   $(this).liveUpdate('ul#teams').focus();
});

Upvotes: 0

Related Questions