Explain Codes LogoExplain Codes Logo

How to trigger event in JavaScript?

javascript
event-dispatching
vanilla-js
event-handling
Nikita BarsukovbyNikita BarsukovΒ·Oct 15, 2024
⚑TLDR

To trigger an event in JavaScript, utilize the dispatchEvent method on an element:

let button = document.getElementById('myButton'); // 🎯 Hit the button! button.dispatchEvent(new Event('click'));

This snippet triggers a click event on a button with id='myButton' - same as if a user clicked it.

Triggering events in depth

While launching a single event is straightforward, crafting nuanced events with parameters or ensuring cross-browser compatibility requires greater depth of understanding. Let's explore the ins and outs of event creation and triggering.

Using CustomEvent for detailed events

For events that need to carry additional data, the CustomEvent interface allows you to incorporate a detail property:

// Harry Potter sending a message via owl πŸ¦‰ let customEvent = new CustomEvent('owlPost', { detail: { message: 'Hello Hogwarts!' } }); button.dispatchEvent(customEvent);

Tackling browser compatibility

Although CustomEvent has good support, older browsers require use of fallbacks. Previously, document.createEvent and initEvent were the go-to methods:

// Want to feel old? This line did your job 10 years ago. var oldEvent = document.createEvent('Event'); oldEvent.initEvent('vintage', true, true); button.dispatchEvent(oldEvent);

However, Internet Explorer 8 or lower needs even more special treatment, using createEventObject and fireEvent:

// Microsoft sends its regards var ieEvent = document.createEventObject(); ieEvent.eventType = 'history'; button.fireEvent('on' + ieEvent.eventType, ieEvent);

Event handling: modern versus legacy browsers

In modern browsers, addEventListener is used for attaching event handlers. If you're supporting older browsers like IE8, you'll have to use the slower attachEvent:

// Hold on tight, we're going time-travelling! ✨ if(button.addEventListener){ button.addEventListener('click', handlerFunction); } else if(button.attachEvent){ button.attachEvent('onclick', handlerFunction); }

Ensuring event integrity

When you trigger events, ensure that these do not clash with the element's inherent actions. Before triggering, always verify the event's type compatibility.

Beyond mere DOM events

Though we primarily discussed DOM events, the art of event dispatching extends to other patterns, such as the Observer and Publish/Subscribe systems.

Farewell jQuery, Hello Vanilla!

A jQuery aficionado might trigger an event using the .trigger() method:

// The easy part $('#myButton').trigger('click');

However, knowing the Vanilla JS equivalent is essential, especially when contemplating performance and dependencies. Resources like "You Might Not Need jQuery" offer guidance.

Catering to your event needs

When you need to trigger a change event on an input to synchronize state in a React component, or other real DOM event reliant frameworks:

let input = document.getElementById('myInput'); input.value = 'new value'; // I've got a value change, yes I do! input.dispatchEvent(new Event('change', { bubbles: true })); // passing the news along πŸ“’

By setting bubbles: true, you allow the event to bubble up through the DOM tree, mimicking actual behavior.