Amy Neville
Amy Neville

Reputation: 10581

How do I add a click event to an inserted element

Ok so I use this button once and then remove it. I then insert a new one. The problem is that the click event stops working. Not sure what is causing this and how I can fix it?

    $("#load_more_button").click(function () {
        //Do things
    }); 

Upvotes: 1

Views: 2315

Answers (1)

bipen
bipen

Reputation: 36531

Actaully you could have got this answer from some other post..there are about 100s of posts with the same issue... click not working for dynamically added element...

Anyways by using .on delegated event you can get it..

$(document).on("click","#load_more_button",function () {
    //Do things
}); 

If you search again you will get all the reasons saying why we need to delegate the events.. so I consider you doing that...

As a note: delegating it to the closest static parent container rather than the document is better performance wise..

Upvotes: 7

Related Questions