0

I noticed that you can make and trigger your own customs events and event listeners in Javascript like this. Can I do something similar to trigger a pre-existing event artificially?

For example say I'm loading external Javascript and I want to artificially trigger DOMContentLoaded after the event has actually fired.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • @mplungjan the method I linked uses an event object which is created. Since I'm not creating an event, I'm using a pre-existing one, I'm not sure how to access that pre-existing event object. – Philip Kirkbride Feb 03 '17 at 14:10
  • http://stackoverflow.com/questions/9153314/manually-dispatchevent-domcontentloaded . So yes. The question just becomes, why would you ever use that over other solutions, since it has a risk of breaking 3rd party code in the project. – Shilly Feb 03 '17 at 14:10

1 Answers1

1

// Code goes here
document.addEventListener('DOMContentLoaded', function(event) {
  console.log('DOMContentLoaded triggered');
});
var event = document.createEvent('Event');
// Define that the event
event.initEvent('DOMContentLoaded', true, true);
// target can be any Element or other EventTarget.
document.dispatchEvent(event);

A more modern approach

The "old-fashioned way" for creating events (as seen above) has been deprecated. It is now better to use the Event constructor instead, as suggested here.

// Code goes here
document.addEventListener('DOMContentLoaded', (event) => {
  console.log('DOMContentLoaded triggered');
});

const event = new Event('DOMContentLoaded', {
  view: window,
  bubbles: true,
  cancelable: true
});
const cancelled = !document.dispatchEvent(event);
if (cancelled) {
  // A handler called preventDefault.
  console.log('The event was cancelled...');
} else {
  // None of the handlers called preventDefault.
  console.log('The event was not cancelled...');
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30