How to trigger event in JavaScript?

In JavaScript, triggering events programmatically allows you to execute event handlers without user interaction. There are several methods to accomplish this, both in vanilla JavaScript and jQuery.

Using jQuery trigger() Method

jQuery's trigger() method fires the specified event and executes its default behavior for selected elements.

<button id="myButton">Click Me</button>

<script>
// Attach event handler
$("#myButton").on("click", function() {
    console.log("Button clicked: " + $(this).text());
});

// Trigger the click event programmatically
$("#myButton").trigger("click");
</script>
Button clicked: Click Me

Using Vanilla JavaScript dispatchEvent()

Modern JavaScript provides the dispatchEvent() method with the Event constructor to trigger custom events.

<button id="vanillaButton">Vanilla Button</button>

<script>
const button = document.getElementById("vanillaButton");

// Add event listener
button.addEventListener("click", function() {
    console.log("Vanilla button clicked!");
});

// Create and dispatch click event
const clickEvent = new Event("click");
button.dispatchEvent(clickEvent);
</script>
Vanilla button clicked!

Triggering Custom Events

You can create and trigger custom events using CustomEvent constructor to pass additional data.

<div id="customDiv">Custom Event Target</div>

<script>
const div = document.getElementById("customDiv");

// Listen for custom event
div.addEventListener("myCustomEvent", function(e) {
    console.log("Custom event triggered with data:", e.detail.message);
});

// Create and trigger custom event with data
const customEvent = new CustomEvent("myCustomEvent", {
    detail: { message: "Hello from custom event!" }
});
div.dispatchEvent(customEvent);
</script>
Custom event triggered with data: Hello from custom event!

Comparison of Methods

Method Library Required Custom Data Support Browser Support
jQuery trigger() Yes Yes All (with jQuery)
dispatchEvent() No Yes (with CustomEvent) Modern browsers

Common Use Cases

Event triggering is useful for automated testing, form validation, and creating interactive user interfaces where one action needs to trigger multiple related events programmatically.

Conclusion

Use jQuery's trigger() for jQuery-based projects or vanilla JavaScript's dispatchEvent() for modern applications. Both methods effectively trigger events programmatically for enhanced user interactions.

Updated on: 2026-03-15T22:14:02+05:30

924 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements