Only Bolivian Here
Only Bolivian Here

Reputation: 36733

Attaching events to elements added dynamically with jQuery

Here's my code:

$("#strong-against .pick .data .actions .btn-success").on("click", function () {
    //Magic here.
});

I read that I should use .on() as that would dynamically attach events to items added even after the document finishes loading.

Yet, the event is not being fired after I load these items dynamically. How can I make it so that any items I add after the document load are listened to?

Upvotes: 0

Views: 204

Answers (1)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try,

$(document).on("click", "#strong-against .pick .data .actions .btn-success", function () {
    //Magic here.
});

Follow the 2 steps to bind event handler for dynamic elements,

  1. Find the closest parent elements to which the element will be added dynamically.
  2. Bind the handler to parent element with the dynamic elements selector as the 2nd argument.

So if #strong-against exist on page load then you can,

 $("#strong-against").on("click", ".pick .data .actions .btn-success", function () {
    //Magic here.
 });

Upvotes: 9

Related Questions