jQuery trigger Equivalent Using Native CustomEvent

Transitioning from jQuery to modern vanilla JavaScript involves replacing convenience methods with standardized Web APIs. In jQuery, the .trigger() method programmatically fires events and executes attached handlers while allowing you to pass custom data. The modern, native JavaScript equivalent to this functionality is the CustomEvent constructor paired with the element.dispatchEvent() method.

The Basic Syntax

In jQuery, triggering a custom event is straightforward:

// jQuery
$('#myElement').trigger('myCustomEvent');

In native JavaScript, you achieve this by creating an instance of CustomEvent and dispatching it using dispatchEvent:

// Vanilla JavaScript
const element = document.querySelector('#myElement');
const event = new CustomEvent('myCustomEvent');

element.dispatchEvent(event);

Passing Data with the Event

A primary use case for jQuery's .trigger() is passing arbitrary data to the event listener:

// jQuery
$('#myElement').trigger('userLogin', [{ username: 'JohnDoe', id: 42 }]);

// jQuery listener
$('#myElement').on('userLogin', function(event, data) {
  console.log(data.username); // "JohnDoe"
});

To pass data using native JavaScript, you must supply an object with a detail property to the CustomEvent constructor. The receiving listener accesses this payload via event.detail:

// Vanilla JavaScript
const element = document.querySelector('#myElement');

const event = new CustomEvent('userLogin', {
  detail: { username: 'JohnDoe', id: 42 }
});

element.dispatchEvent(event);

// Native listener
element.addEventListener('userLogin', (event) => {
  console.log(event.detail.username); // "JohnDoe"
});

Handling Event Bubbling

By default, jQuery's .trigger() allows events to bubble up the DOM tree. Conversely, native CustomEvent instances do not bubble unless explicitly configured to do so.

To match jQuery's default behavior, set bubbles: true in the configuration options:

const bubblingEvent = new CustomEvent('userLogin', {
  detail: { username: 'JohnDoe' },
  bubbles: true,      // Allows the event to bubble up through parent nodes
  cancelable: true   // Allows event.preventDefault() to cancel the event
});

element.dispatchEvent(bubblingEvent);

Standard DOM Events vs. CustomEvent

If your goal is to trigger an existing, standard DOM event (such as click, focus, or submit) without custom data, you can often use dedicated helper methods:

// Native click simulation
element.click();

For broader event compatibility without custom payloads, standard events can also be dispatched using the generic Event constructor:

element.dispatchEvent(new Event('change', { bubbles: true }));

For all scenarios requiring custom naming, custom payloads, or specialized configuration, the CustomEvent API is the complete native alternative to jQuery's .trigger().