views:

71

answers:

1

Fellow JQuery hackers, hello :-)

Suppose you have the following code:

$('.links').click(function(){
    //Do something
}

And I then insert dynamic content into a DIV's HTML content (Say, for example, after clicking a button, the new content gets inserted). This content has the "links" class. The problem is that the "click" button doesn't get registered with the newly inserted content.

How do I tell JQuery to re-select all the elements with a "links" class and apply the above function on them? Can this be automated?

Thanks.

+10  A: 

You'll want to use event delegation:

$('.links').live("click",function(){
    //Do something
});

That will prevent dynamically inserted elements with the class links from losing their click event handler. Note that you will also need jQuery 1.3 or later for that to work. See Events/live.

Another way is to re-bind using the callback of whichever of jQuery's ajax methods you have opted to use, example:

$('#someDiv').load('page.html', function() {
    $('.links').click(function(){
        //Do something
    });
});

or neater still:

function initLinks() {
    $('.links').click(function(){
        //Do something
    }
}

$('#someDiv').load('page.html',initLinks);
karim79
WARNING: there is an error with using live with FF. If you do right clicking something that is ".live"ed will be counted as being left clicked.
Dorjan
Apart from that, use the above (I've even voted it up myself, I just wanted to throw that extra info in for you)
Dorjan
Wow, good catch on that bug! A workaround for that would be to filter for left mouse button clicks: function(e) { if (e.button == 0) { // 0 = left, 1 = middle, 2 = right } }
Joe Chung