Use the dispatchEvent Method
We can use the
dispatchEvent method on an element to trigger an event programmatically.
For instance, if we have the following HTML:
We can write:
const element = document.querySelector('input'); element.addEventListener('change', () => console.log('change')) const event = new Event('change'); element.dispatchEvent(event);
to trigger the change event on an input.
We get the input with
Then we add a change event listener with the
Then we create a new event with the
'change' sets it to create the change event.
And then we call
element.dispatchEvent to trigger the event we created.
Therefore, we should see
'change' logged from the change event listener.
We can trigger the change event programmatically on an input element with the
Then we can call the
dispatchEvent method to dispatch the event.