Based on the answer by Peter and my own work with modern JavaScript, I added this tiny jQuery extension function to my code. It employs current standard recommendations (as of 2022), as far as that's possible with jQuery. All the other referenced content, including the jQuery learning center, uses deprecated APIs.
// Triggers a native event. This will also be visible for
// native event listeners, unlike jQuery events.
$.fn.triggerNative = function (type) {
return this.each(function() {
this.dispatchEvent(new CustomEvent(type));
});
};
This little tool will help me out migrating old jQuery plugins to native code and use their events in the real world outside the jQuery bubble as expected. It might miss out some special features, but it's totally enough to make a simple change
event seen elsewhere.
It also works for custom event types that you use internally in your code. These events are also fully visible in the jQuery on()
event handlers. So no reason not to use this if it does what you need.
// Old code:
$(element).change();
$(element).trigger("change");
// New code:
$(element).triggerNative("change");
Don't expect Internet Explorer support from me anymore, that browser will be officially unsupported and finally left to rot in a few weeks. Should work in classic Edge though (already unsupported).
Update: I made some extensions so that this function meets all my requirements. I now use this exclusively. It can pass data to the event and use the event afterwards to see if it has been cancelled (only for a single target element) or what data was written to it in a handler. All events now also bubble as in jQuery by default.
// Triggers a native event. This will also be visible for native
// event listeners, unlike jQuery events. The native event will
// bubble and be (formally) cancelable.
// Returns the event object triggered for the first selected Node.
//
// type: (String) The event type name.
// data: (Object) An object containing additional event properties
// to be set. (Optional)
$.fn.triggerNative = function (type, data) {
let event;
this.each(function() {
let thisEvent = new CustomEvent(type, {
bubbles: true,
cancelable: true
});
if (!event)
event = thisEvent;
Object.assign(thisEvent, data);
this.dispatchEvent(thisEvent);
});
return event;
};
Use like so:
// Pass drag point with event
let event = $(element).triggerNative("draggablemove", { newPoint: p });
if (!event.defaultPrevented) {
// Consider restricted drag point
console.log(p, event.newPoint);
}