-1

I have an OL that contains LIs with small inset buttons:

<li id="123">
  <button class="action1">Do 1</button>
  <button class="action2">Do 2</button>
</li>

And my jquery which has set up the functions on document load:

$('.action1').on('click', function() {
  // do stuff
});

Only, when I'm appending to the list:

li = '<li...' //defines li item here
$('#myol').append(li);

The buttons don't do anything. I guess this is because the listeners were attached before the listitem was created, but what is the correct way to attach the listeners to the newly created items (or even better, set them up in such a way that newly created items are accounted for?

user4893295
  • 533
  • 6
  • 25
  • See this question: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Bas van Dijk Jun 06 '17 at 11:27
  • Though this is correct, an efficient way would be to have `li` call a function `onclick` and append `li` with an `onclick` – Saksham Jun 06 '17 at 11:35

1 Answers1

0

You can attach event to your dynamic element like that:

$('body').on('click', '.action1', function() {
    // do something
});

This will work for all a tags with class 'action1' in the body, whether already present or dynamically added later.

Victor Leontyev
  • 8,488
  • 2
  • 16
  • 36