227 of 264 menu

new Event statement

The new Event statement is an event constructor with which you can create an event object and then call this event from JavaScript using the dispatchEvent method. Why do you need it: you can simulate a user clicking on a button, trying to submit a form, and so on. In this case, the event will not differ from the real one except for the event.isTrusted property. You can even create events with non-standard (invented by you) names and then call them at the right time.

Syntax

new Event(event type, [options]);

Example

Let's say we have a button. When this button is pressed, a message is displayed. Let's make it so that when you hover over a button, this button thinks that it was clicked:

<button id="button">button</button> let button = document.querySelector('#button'); button.addEventListener('click', function() { alert('message'); }); button.addEventListener('mouseover', function() { let clickEvent = new Event('click'); // we create the event this.dispatchEvent(clickEvent); // simulate the button click });

:

Example

You can create your own events (with your own name) and then call them at the right time. Let's bind the showMessage event to a button and fire this event on hover:

<button id="button">button</button> let button = document.querySelector('#button'); button.addEventListener('showMessage', function() { alert('message'); }); button.addEventListener('mouseover', function() { let showMessageEvent = new Event('showMessage'); // we create an event this.dispatchEvent(showMessageEvent); // trigger the event });

:

See also

byenru