Does anyone know the magic required to get jQuery .trigger()
to trigger a custom event that's handled by a (not jQuery) native JavaScript event handler?
test = document.querySelectorAll('.test')[0];
test.addEventListener('click', function() {
console.log('click')
});
test.addEventListener('custom', function(ev) {
console.log('custom', ev.detail)
});
// Custom Native -> Native works as expected
test.dispatchEvent(new CustomEvent('custom', {detail: 'detail'})); // -> "custom" "detail"
// Standard jQuery -> Native works as expected
$(test).trigger('click'); // -> "click"
// Custom jQuery -> Native does not work
$(test).trigger('custom'); // -> No log?
$(test).trigger({type: 'custom'}); // -> No log?
codepen.io live example
Edited to add:
A bit more details on my use case. I'm developing a library that relies on custom events but doesn't itself use jQuery. However, I'd like to make the library convenient for those applications that do have jQuery.
Well, after stepping through the jQuery source in a debugger, it looks like there is a solution. Not elegant, but workable. The trick is to add an onxxxx
property to the element, where xxxx
is the event name. The addition to the code in the question would be:
test.oncustom = function(ev, data) {
// ev is the jQuery Event object
// data is data passed to jQuery `.trigger()`
}
Note that jQuery does not add custom data to, for example, ev.detail
, as would be the case for a standard event. Instead it passes custom data as an additional parameter.
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