DaSch DaSch - 11 months ago 72
TypeScript Question

document.addEventListener vs. $(document).on

I somehow found a bit strange behavior of adding eventlisteners to document. While adding listeners to HTMLElements works fine adding a listener to document doesn't work. But the strange thing is, that using jQuery makes it work.

So can someone explain, why this two functions are not doing the exact same thing?

["customEvent1", "customEvent2"].forEach(
(event: string) => {
document.addEventListener(event, () => this.eventHandler());

$(document).on("customEvent1 customEvent2", () => this.eventHandler());

Well it seams that there is some misunderstanding about the environment.

  1. The function is surrounded by a class

  2. I'm using TypeScript/ES6

  3. the EventHandler is a class method

  4. the custom event is triggered with

Answer Source

jQuery does not create a native event if you use $(document).trigger("customEvent2"); (jquery src/event/trigger.js), it only emulates the native event handling.

So if you register an event handler using document.addEventListener then your cannot use $(document).trigger( for those events.

But if you create and dispatch an event using native code:

var event = new Event('customEvent1');

Then you can catch it with both document.addEventListener and jQuery's .on