Recently, I came across an odd behavior while trying to add event listeners to the document. Strangely, when adding listeners to HTMLElements, everything worked smoothly, but for some reason, adding a listener to the document did not have any effect. However, strangely enough, using jQuery made it work perfectly.
I am puzzled as to why these two functions are not functioning in the same way. Can anyone shed light on this discrepancy?
["customEvent1", "customEvent2"].forEach(
(event: string) => {
document.addEventListener(event, () => this.eventHandler());
});
$(document).on("customEvent1 customEvent2", () => this.eventHandler());
EDIT: It appears that there may be some confusion about the setup:
- The function is contained within a class
- I am utilizing TypeScript/ES6
- The EventHandler is a class method
- The custom event is triggered with
;$(document).trigger("customEvent1")