Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
Dejan Avatar asked Dec 14 '10 18:12

Dejan


2 Answers

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() {
like image 129
Nick Craver Avatar answered Oct 03 '22 21:10

Nick Craver


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

like image 20
Erik Avatar answered Oct 03 '22 22:10

Erik