Let's say I want to change the text of any new particular DOM elements that are created. E.g.:
(not real API, I realize)
$('body').on('creation', '.change-this', function() {
$(this).text('Boom!');
});
So if I programmatically create <p class="change-this">
and add it to the DOM (via jQuery or otherwise), the above fires off. Is this something jQuery can do? All I can think of, is when I add whatever HTML programmatically, to do a $.trigger('creation')
and have a handler ready to take care of those events.
You want to track your brand new items? You can do this using custom events. Since you are using jQuery, you may use the method
.trigger()
to create your event.For instance, you will need to trigger your event every time you create your element. So, in your code you will add something like this:
Then, you will create a listener for this custom event:
Check this snippet:
Bear in mind that if you want to track elements with custom tracks, you just need to create different custom events and handle its triggers.
So, that's it. jQuery provide us a simple and beautiful way to work with custom events. Awesome!
For further information, you may check these links: jQuery.trigger() - http://api.jquery.com/trigger/
Introducing Custom Events - http://learn.jquery.com/events/introduction-to-custom-events/
CustomEvent - https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
Good Luck!