0

I am trying to trigger an event when clicking on buttons that get inserted via ajax into a div. My buttons have the class btn.

The code below works only on buttons that were already in the DOM:

$('.btn').click(function(){
    alert('It works!');
});

I am using the MutationObserver example from MDN to recognize a new child node has been made to my div and I do get a response in my console with: A child node has been added or removed.

How to make jQuery also recognize this child node and its attributes so i can trigger events with my inserted buttons?

SLT
  • 43
  • 7
  • 1
    Use [event delegation](https://stackoverflow.com/a/12230108): attach the listener on a mutual parent and specify the selector: $('mututal parent selector').on('click, '.btn', function() { ... }) – wOxxOm Mar 08 '19 at 14:00
  • @wOxxOm This works. Thank you! – SLT Mar 08 '19 at 14:18

2 Answers2

0

You simply need to use the .on() method:

$('.btn').on("click", (function(){
    alert('It works!');
});
Anurag Srivastava
  • 12,230
  • 3
  • 21
  • 36
  • This gives the same results unfortunately. It works on my already existing buttons but not the newly added ones. – SLT Mar 08 '19 at 14:04
0

As stated by wOxxOm I had to use event delegation in order to make it work.

$('#divID').on('click','.btn', (function(){
    alert('It works!');
});
SLT
  • 43
  • 7