jquery add listener to appended content
Asked Answered
H

3

7

I have some jQuery code like this:

$("#add").click(function(event){
    $("#list").append('<a class="remove" href="#">x</a>');

    return false;
});

$('.remove').live('click', function(){
    alert("123");
});

If one clicked on class=remove I would like it to alert 123. This doesn't happen though. I think this is a simple idea but I must be missing something.

Any ideas?

Thanks.

Hayleyhayloft answered 12/2, 2013 at 13:5 Comment(1)
You need to delegate.Kokand
R
13

Live is deprecated, use on

$(document).on('click','.remove',function(){
alert("123");
});
Ruano answered 12/2, 2013 at 13:6 Comment(4)
and you do the document click to bind to something that is present at load timeAlmita
I see that it does do event delegation in the manner that you are using it. Interesting. Thanks for this.Kokand
Yes, if a selector is present it is a delegated event handler. Read more here: api.jquery.com/onUntouchable
This is definitely the best answer in my opinion.Kokand
C
2

Another way to add element and bind event without delegation:

$("#add").click(function(event){
    $("<a />", {
        "class": "remove",
        href: "#",
        text: "x"
    }).on("click", function() {
        alert("123");
        return false;
    }).appendTo("#list");

    return false;
});

Avoid using live method, since it was deprecated and finally removed in the last version of jQuery.

Cribriform answered 12/2, 2013 at 13:7 Comment(0)
F
2

try on delegate function..since you are apending that to list... you can use #list which is better in performance that the document

 $('#list').on('click','.remove', function(){
     alert("123");
});

you can go through the link to read more about on() event

Fardel answered 12/2, 2013 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.