tags:

views:

28

answers:

2

I have appended a div to my body

$('<div id="container"><img class="large" src="'+ img +'" /><a href="#">previous</a> | <a href="#" class="next">next</a></div>').appendTo('body').hide().fadeIn();  

But i cannot interact with the elements that i;ve added if i try something like

$('a.next').click(function(){
    $(this).remove();
    });

it doesn't work .. how can i make jquery take notice of the appended elements ?

+1  A: 

Use .live() to recognize current and future elements matching the selector, like this:

$('a.next').live('click', function(){
  $(this).remove();
});

Why doesn't it work currently? This part: $('a.next') says "find <a class="next"> that exist", then do something to them...but those links you're dynamically adding don't exist at that time, they're created later, so you need a different approach.

Nick Craver
I was sure that the problem was caused by the fact that the content is later added but I didn;t know how to solve it. thx.
andrei
+2  A: 

you need to

  • either defer attachment of the click handler until after the a tag has been inserted into the document
  • or use jquery.delegate or jquery.live so that you don't need to care
just somebody