Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger event in JavaScript?

I have attached an event to a text box using addEventListener. It works fine. My problem arose when I wanted to trigger the event programmatically from another function.

How can I do it?

like image 722
KoolKabin Avatar asked Mar 22 '10 08:03

KoolKabin


People also ask

Can JavaScript trigger events?

HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document.

How can I trigger a click event in JavaScript?

Trigger Click Event in JavaScript Using click() An element receives the click event when pressed, and a key is released on the pointing device (eg, the left mouse button) while the pointer is within the element. click() is triggered after the down and up mouse events are triggered in that order.

What is a trigger in JavaScript?

The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.


2 Answers

Note: the initEvent method is now deprecated. Other answers feature up-to-date and recommended practice.


You can use fireEvent on IE 8 or lower, and W3C's dispatchEvent on most other browsers. To create the event you want to fire, you can use either createEvent or createEventObject depending on the browser.

Here is a self-explanatory piece of code (from prototype) that fires an event dataavailable on an element:

var event; // The custom event that will be created if(document.createEvent){     event = document.createEvent("HTMLEvents");     event.initEvent("dataavailable", true, true);     event.eventName = "dataavailable";     element.dispatchEvent(event); } else {     event = document.createEventObject();     event.eventName = "dataavailable";     event.eventType = "dataavailable";     element.fireEvent("on" + event.eventType, event); } 
like image 104
Alsciende Avatar answered Sep 19 '22 16:09

Alsciende


A working example:

// Add an event listener document.addEventListener("name-of-event", function(e) {   console.log(e.detail); // Prints "Example of an event" });  // Create the event var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });  // Dispatch/Trigger/Fire the event document.dispatchEvent(event); 

For older browsers polyfill and more complex examples, see MDN docs.

See support tables for EventTarget.dispatchEvent and CustomEvent.

like image 44
Dorian Avatar answered Sep 18 '22 16:09

Dorian