dispatchEvent method

The dispatchEvent method allows you to simulate an event on an element. 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 (your own) names and then call them at the right time. The method is applied to the element on which the event is to be fired. As a parameter, the method receives an event (object) created using the new Event constructor.

Syntax

javascriptelement.dispatchEvent(event);

Example

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

html<button id="button">button</button>
javascriptlet 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 initialize this event on hover:

html<button id="button">button</button>
javascriptlet button = document.querySelector('#button');

button.addEventListener('showMessage', function() {
  alert('message');
});

button.addEventListener('mouseover', function() {
  let showMessageEvent = new Event('showMessage'); // we create the event
  this.dispatchEvent(showMessageEvent); // trigger the event
});

Результат: