Tiffany Brown by Tiffany Brown in Blog

Post tags: constructors dom domcore event eventtarget odin web-standards

This post is licensed under a Creative Commons Attribution 3.0 Unported license.

DOM Event Constructors in Opera 11.60

As mentioned in Divya's post about what's new in Opera 11.60, Opera now supports the DOM Event constructor syntax. It offers a simpler way to create synthetic and custom DOM events.

Why might you use a synthetic event or a custom event? Synthetic events can be useful for automated testing, or for developing user interfaces that change conditionally based on user input. Custom events work particularly well for game development, where you may, for example, dispatch a shoot event when the user presses the space key.

Creating a synthetic event

Let’s take a look at how we used to create a synthetic event by constructing a focus event on an input element.

var event = document.createEvent('Event');
event.initEvent('focus', false, true);
document.querySelector('input').dispatchEvent(event);

First, we create the event object using the createEvent() method. Then we initialize it using initEvent(), and dispatch it to the input element using dispatchEvent(). Now let's create the same event using the Event() constructor and compare.

var event = new Event('focus', {bubbles:false,cancelable:true});
document.querySelector('input').dispatchEvent(event);

We now need just two lines of code: one to create the event, and one to dispatch it. Our first argument is the name of the event we would like to dispatch. Our second argument is optional. It is a dictionary, a collection of key-value pairs that define the properties of the event. What those properties should be depends on the type of event you are synthesizing. A MouseEvent, for example, should include screenX and screenY properties. In this case, however, we are just setting the bubbles and cancelable properties.

Custom events

Custom events have a similar syntax, but use the CustomEvent() constructor. In the example that follows, we're creating and dispatching a ripple event on the document.

document.dispatchEvent( new CustomEvent('ripple', {x:40, y:20}) );

The above example demonstrates another advantage of the constructor syntax: the ability to create a new event as a parameter for dispatchEvent().

Though a switch from the way we currently dispatch events, DOM Event constructors offer us greater flexibility and a cleaner syntax.

Current browser support

Opera is not the only browser that supports DOM Event constructors. They are also available in recent WebKit builds, including the latest version of Chrome.