11

I have a div with class="tags" with one predefined hyperlink.

<div class="tags">
     <a href="#">myLink</a>
</div>

And I have function to remove that hyperlink if user clicks on it.

$('.tags a').click(function() {
    $(this).remove();
    return false;
});

And this works with predefined hyperlinks. If I add another links with the help of jQuery (after the page is loaded)

$('.tags').append('<a href="#">newLink</a>');

Function to remove hyperlink (on click) won't be called on these, added links. How to solve this?

svenkapudija
  • 5,128
  • 14
  • 68
  • 96

2 Answers2

6

You have to use the live-function:

$(".tags a").live("click", function() {
    // ...
});

Because you are adding the links after the initial load, the standard click event won't be binded to the dynamic added links.

Matt
  • 74,352
  • 26
  • 153
  • 180
kufi
  • 2,418
  • 19
  • 14
  • 21
    **Note** that [`live()`](http://api.jquery.com/live) has been depreciated since 1.7. It's advisable to use [`on()`](http://api.jquery.com/on) from now on. The translated call would be `$(document).on('click', '.tags a', function () { /* foo */ });` – Matt Mar 12 '12 at 10:51
  • Thanks. Should I use it on all my clicks/similar actions or only when really needed? – svenkapudija Mar 12 '12 at 10:51
  • 1
    For the performance, look at this answer: http://stackoverflow.com/questions/6047193/liveclick-and-performance I personally prefer to use the click-event and only use the live-event if I really need it, as it is clear that there will be dynamic added elements. – kufi Mar 12 '12 at 10:54
0

Your click event only attached to current dom element not to future element.If you want to add this event to all element include future then you have to use live event in jquery. http://jsfiddle.net/6cGvt/

sandeep
  • 2,244
  • 1
  • 23
  • 38
  • 6
    **Note** that [`live()`](http://api.jquery.com/live) has been depreciated since 1.7. It's advisable to use [`on()`](http://api.jquery.com/on) from now on. The translated call would be `$(document).on('click', '.tags a', function () { /* foo */ });` – Matt Mar 12 '12 at 10:53
  • Yup,...For latest version in jquery .you have to use ON method – sandeep Mar 12 '12 at 10:55