1

A couple of minutes ago I faced a situation where I needed to do some functions whenever some events were triggered like:

<button>Default button</button> and then a script like:

$('button').click(() => $('body').append(`<button>Re-rendered button</button>`));

So I was searching for a $(document).change() function and I found this solution that worked great for my situation:

$(document).bind('DOMContentLoaded DOMSubtreeModified', () => {
  $('button').on('click', () => {
    $('body').append(`<p><button>Another button</button></p>`);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>First Button</button>

In fact, this code here adds three buttons, but on CodePen works as intended.

So, the question is, how should I apply (as a best practice) the same logic in order to let the new buttons be affected by jQuery functions?

Martin Fernandez
  • 368
  • 5
  • 16
  • 1
    Don't use `DOMSubtreeModified` - it's been deprecated for some time. If you wanted to do this in this manner, use a MutationObserver. ***However*** as you're using jQuery just use a delegated event handler. – Rory McCrossan Oct 05 '18 at 18:47
  • 1
    It will also compound more events onto the previously created buttons. Meaning if you hit one of the previous buttons you will get increasingly more buttons each time you click one. – Patrick Evans Oct 05 '18 at 18:51

0 Answers0