Dejan
Dejan

Reputation: 207

jQuery click on appended elements

I have generated some html links with jQuery and appended it to some div but it seams that i can't call click method now, when these elements are appended (it worked ok when they were hardcoded into html) $('#something a').click(function() ...

Does anyone know a solution for this?

Upvotes: 12

Views: 9800

Answers (3)

Erik
Erik

Reputation: 41

What also works is to add the [click] event when appending the elements, like so:

$('<someElement>').click(function(){ 
    $('<someElement>').append('<htmlCodeToAppend>');
    $('<appendedElement>').click(function() { /* do something */ });
});

This approach does the job, but I'm not sure if there are any caveats to it -- maybe one of the pros could kindly step in here.

Cheers, Erik

Upvotes: 4

GSto
GSto

Reputation: 42380

you need to use the live function to make sure that the click event gets binded to elements that have been added to the DOM after the page has been loaded:

$('#something a').live('click',function() .....

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630627

Use .delegate() for these cases:

$('#something').delegate('a', 'click', function() {

This attaches a click handler on #something, rather than direction to the <a> elements within...so it works on anchors appended later. The alternative (worse for a few reasons) version is .live() like this:

$('#something a').live('click', function() {

Upvotes: 21

Related Questions