user971637
user971637

Reputation:

Create and trigger a window event automatically

How to create and triggent an event in javascript ?

For example I imagine something like this:

window['myevent'] = function() {alert('myevent was triggered automatically');}
window['myevent'](window);

basically i want to create my event and trigger it when i need automatically in a function

Upvotes: 1

Views: 162

Answers (1)

Andy G
Andy G

Reputation: 19367

Your code works (did you try it) but there is no need to pass the (window) argument - your function/event isn't expecting an argument.

window['myevent']();

There is a more formal guide here at SitePoint which demonstrates using addEventListener with custom events, and using dispatchEvent to trigger the event on an element.

Note: IE 9 and below do not support the CustomEvent object. If you are using a JS Library, however, then most libraries support some form of custom event delegation.

Upvotes: 1

Related Questions