Triggering built-in and custom events using JavaScript

There are different ways to trigger an event on an HTML element in JavaScript. Some elements provide built-in methods for triggering different kinds of events.

For example, to trigger a click event on any HTML element, you can use the click() method of the element DOM object:

const btn = document.querySelector('button');
btn.click();

Similarly, the <input> and <textarea> HTML elements provide the focus() and blur() methods to trigger the focus and blur events:

const input = document.querySelector('input');

// Focus input element
input.focus();

// Blur input element
input.blur();

The <form> element offers the submit() and reset() methods for triggering the submit() and reset events:

const form = document.querySelector('form');

// Trigger submit event
form.submit();

// Trigger reset event
form.reset();

Triggering built-in events

To trigger other events such as the change or keyup, you need to create an Event object and pass it to the dispatchEvent() method of the element object as shown below:

const select = document.querySelector('select');

// Listen for change event
select.addEventListener('change', (e) => {
    console.log(`A new value is selected.`);
});

// Programmatically trigger `change` event
const event = new Event('change');

select.dispatchEvent(event);

In the above example, we first registered an event handler to the change event of the <select> element, then created a new event by using the Event constructor, and finally used the dispatchEvent() method to trigger the change event.

Triggering a custom event

The Event constructor can also be used to trigger a custom event as shown below:

// Listen for `hello` event
select.addEventListener('hello', (e) => {
    console.log(`Hey there!`);
});

// Programmatically trigger `hello` event
const event = new Event('hello');

select.dispatchEvent(event);

Passing custom data – CustomEvent()

To pass more data to the event object, You can use the CustomEvent() constructor instead. It accepts an optional object as a second parameter that can be used to define event properties. The detail property of the optional object can be used to pass custom data.

Let us say you have the following <time> element:

<time data-time="2020-09-29T13:58:25.546Z">Sep 29th, 2020</time>

The following example demonstrates how you can trigger a custom event called buildTime and pass additional data to the event object:

// Define an event handler
const handler = (e) => {
    console.log(`Build time is ${e.detail}`);
};

// Listen for `buildTime` custom event
document.addEventListener('buildTime', handler);

// Trigger `buildTime` custom event
const time = document.querySelector('time');

const event = new CustomEvent('buildTime', {
    detail: time.dataset.time
});

document.dispatchEvent(event);

The old-fashioned way

The Event constructor works in all modern browsers except Internet Explorer. To support old browsers like IE9+, you can use the document.createEvent() method to create an trigger an event as shown below:

const elem = document.querySelector('button');

// Define an event handler
const handler = (e) => {
    console.log(`Event is triggered!`);
};

// Listen for `awesome` event
elem.addEventListener('awesome', handler);

// Create an event - IE9+
const event = document.createEvent('Event');

// Define the event name
event.initEvent('awesome', false, true);

// Trigger `awesome` event
elem.dispatchEvent(event);

Event bubbling

Sometimes you may want to trigger an event from the child element and capture it on a parent element. To do so, just set the bubbles property to true.

Let us say you have the following HTML code snippet:

<form>
    <input type="text" name="name">
</form>

The following example shows how you can trigger an event on <input> and capture it on the <form> element:

const form = document.querySelector('form');
const input = document.querySelector('input');

// Create a new event with bubbling allowed
const event = new CustomEvent('name', {
    bubbles: true,
    detail: {
        text: () => input.value
    }
});

// Listen for `name` event on form
form.addEventListener('name', (e) => {
    console.log(`My name is ${e.detail.text()}`);
});

// Trigger `name` event from input when the user types
input.addEventListener('keyup', (e) => {
    e.target.dispatchEvent(event);
});

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.