12

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?

bcm
  • 5,470
  • 10
  • 59
  • 92
Dejan
  • 207
  • 1
  • 3
  • 6

3 Answers3

21

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() {
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • @Nick - why is using live worse? Just curious because I use it a lot. – Josh Dec 14 '10 at 18:26
  • @Nick - could you please comment on the reasons why .live() is worse - I'm genuinely interested. Cheers! – Jakub Konecki Dec 14 '10 at 18:26
  • 4
    @Josh, @Jakub - With `.live()`, let's take the code above - the `$('#something a')` selector is run immediately, but we don't care what it found...the result is wasted. Also since it attaches to `document`, *every* `click` must be checked against that selector. With `.delegate()` only the very fast `$('#something')` selector get runs, and we use the result. Also only clicks from within `#something` need to be checked, since they're checked at that parent, so `.delegate()` addresses 2 performance reasons...with a more expensive selector, the gains are even greater. – Nick Craver Dec 14 '10 at 18:28
  • Ugh Nick I hate you (not really), I implemented a delegate like thing (except this points always to the element triggering) only to realize a few weeks later jquery done it. O well thats what I get for not reading the whole api. – Dmitriy Likhten May 17 '11 at 18:35
  • +1 This answer helped me. By the way, one year later, as jQuery 1.7+, the [`.on()`](http://api.jquery.com/on/) superseded .delegate() – RaphaelDDL Jan 02 '12 at 17:05
4

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

Erik
  • 41
  • 1
0

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() .....
GSto
  • 41,512
  • 37
  • 133
  • 184