Event Triggers
You have seen that events are dispatched dynamically when interacting with a web page, but events can also be triggered manually, through your own code.
As we mentioned previously, events in JavaScript are typed objects. When a dynamic event is raised, the JavaScript engine creates such an object and dispatches it. The object contains a type value that stores the event type as a string, such as click
.
It is possible to instantiate your own event objects and dispatch them, rather than simply relying on events being created dynamically. There are many reasons why you might like to do this, such as to simulate user interaction or to easily invoke code already assigned as an event handler without duplicating code. To do so, you simply create an instance of an Event
using the new
keyword and pass it the type of event you wish to raise:
var ev = new Event("click");
Once created, you then simply dispatch it using the node's dispatchEvent
method: