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?

2 Answers 2

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.

3
  • 21
    Note that live() has been depreciated since 1.7. It's advisable to use on() from now on. The translated call would be $(document).on('click', '.tags a', function () { /* foo */ });
    – Matt
    Mar 12, 2012 at 10:51
  • Thanks. Should I use it on all my clicks/similar actions or only when really needed? Mar 12, 2012 at 10:51
  • 1
    For the performance, look at this answer: 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, 2012 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/

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.