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.
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.
Share Improve this question asked Oct 17, 2014 at 11:10 BogdanBogdan 44.5k12 gold badges129 silver badges130 bronze badges 2 |1 Answer
Reset to default 18By 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>
$(this).trigger("custom_event")
, but I'm guessing you have a reason for the straight DOM code in the above (perhaps a non-jQuery library you want to be compatible with jQuery code using it?). – T.J. Crowder Commented Oct 17, 2014 at 11:15