I have the following code that triggers a custom named event:
elem.addEventListener('click', function (event)
{
event.preventDefault();
// Do some processing stuff
var event = new Event('custom_event');
this.dispatchEvent(event);
});
If I try to catch the custom event with jQuery.on() it works, but only when I'm not using the descendant selector filter.
So this works:
$('selector').on('custom_event', function () { // works });
But this doesn't:
$(document).on('custom_event', 'selector', function () { // doesn't work });
Can anyone shed some light on why that is? Here's a Fiddle showing the problem.
By default the event does not bubble, so when you create an event you need to pass bubbles: true
as an option to indicate that you want the event to be bubbled. You can use CustomEvent to do that.
You are using event delegation to register the second handler which makes use of event bubbling to work.
document.querySelectorAll('.button')[0].addEventListener('click', function(e) {
var event = new CustomEvent('custom_event', {
bubbles: true
});
this.dispatchEvent(event);
});
$(document).on('custom_event', '.button', function() {
alert('Custom event captured [selector filter]');
});
$('.button').on('custom_event', function() {
alert('Custom event captured');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="button">Click Me</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With