JavaScript/Handling DOM events

Applications with a user interface - and other application types - are predominantly driven by events. Here we focus on DOM events. They originate (or fire) from specific actions or situations in a browser or a native app, e.g., a user clicks with the mouse, types a keyboard key, or works on a touch screen; a visual object is 'dragged & dropped', 'copied & pasted', or resized; the HTML page is loaded or shall be unloaded; the browser or a visual object gets or loses the focus; and much more. It's also possible that the application creates events programmatically (dispatch).

An event is related to its originating object and with a JavaScript statement; that is, in most cases, a call to a function that is denoted as the event handler. The JavaScript part is invoked after the event arises. Common actions are communication with a server, validation of user input, or modification of DOM or graphics.

Embedded in HTML
A short example shows how events are defined in an HTML page, fire, and execute. This syntax version is denoted as inline JavaScript.

When a user clicks on one of the buttons, the browser reads the button's attribute, creates a JavaScript object that contains all properties of the event, and executes the JavaScript statement(s). Mostly, the JavaScript part is a call to a function. That function is denoted the event handler. It receives the JavaScript object as its first parameter. Only in very simple cases, the complete JavaScript script is inlined.

Of course, the called function must exist somewhere. Some standard functions like  are predefined and provided by the browser. Your self-written functions exist within the HTML tag, or the tag refers to a file or URL where they exist.

Hint: Embedding event definitions directly into HTML is called inline JavaScript. It's the earliest method of registering event handlers, but it tends to make the source hard to read for non-trivial applications. Therefore it can be seen as being a less desirable technique than other unobtrusive techniques; see next chapter. The use of inline JavaScript can be considered to be similar in nature to that of using inline CSS, where HTML is styled by putting CSS in  attributes.

Nevertheless, the Wikibook on hand will use inline JavaScript often in its demonstration pages because the syntax is short and the concept is easy to understand.

Programmatically in JavaScript
JavaScript knows two ways to register an event handler for an HTML element. First, the event handler function can be directly assigned to the element's properties  (onclick, onkeydown, onload, onfocus, ...). Their name starts with 'on' and ends with the value of the event type. Second, the function  registers the event type and the event handler.

The onclick event handler 'register' of button 'button_1' is registered with the above inline JavaScript syntax. When the page loads, only this event handler is known. Clicks to the paragraph 'p1' don't trigger any action because it does not have any event handler so far. But when the button gets pressed, the handler of button 'button_1' registers the second event handler, the function 'showMessage'. Now, after a click on the paragraph, the alert "A click-event to the paragraph..." occurs.

The registration is done in line 10. The noticeable difference to the inline JavaScript is that there are no parenthesizes. The inline JavaScript calls the function  and hence needs to use parenthesizes. The function  does NOT call. It uses only its name for the registration process.

The alternative to assigning the function to the paragraph's 'onclick' property is the use of the function. It acts on the element 'p1' and takes two parameters. The first one is the event type (click, keydown, ...). Such event types correlate with the onxxx names in that they miss the first two characters 'on'. The second parameter is the name of the function that acts as the event handler.

You can test the example by commenting out either line 10 or line 12. Line 12 with the  function is the preferred version.

Event types
Different kinds of events exist depending on the kind of the originating element. The complete list of event types is incredibly huge (MDN) (W3schools). We show some important types and examples.

The following example demonstrates some different event types.

When the page is loaded, the onload event of the  is fired. Please notice that here the 'on' prefix is necessary because it's the inline JavaScript syntax (line 23). The called function registerAllEvents locates diverse HTML elements and registers event handlers of different types (lines 8 - 13). Often you will register different functions, but to keep things easy, we register in this example the same function handleAllEvents to all elements. This function reports the event type and the originating HTML element.

Event properties
The event is always passed to the event handler as its first parameter in the form of a JavaScript object. JavaScript objects consist of properties; properties are key/value pairs. In all cases, one of the keys is 'type'. It contains the event's type; some of its possible values are shown in the above table. Depending on the event type, a lot of other properties are available.

Here are some examples of more or less important properties.

An example of accessing a property is given in the following script.

A mouse-move event is registered for the. Whenever the mouse moves across the body, the event is triggered. The event handler reads the x/y properties out of the JavaScript object and shows them in the title of the browser's active tab.

removeEventListener
Similar to  the function   removes an event listener from an element.

Synthetic events
The system offers the above-shown rich set of event types. Additionally, you can create your own events and trigger them from your application.

First, you create a function with one parameter, the event handler. Next, you register this event handler for an element. So far, everything is the same as with predefined event types.

Now you can trigger this event in any part of your application. To do so, you create a new event of precisely the chosen type and fire it with a call to.

For test purposes, we bind this functionality to the button. The complete page now looks like this:

At the beginning, the button listens to click events, and 'p1' listens to events of type 'click' as well as of type 'syntheticEvent'. When the button is clicked, his event handler 'triggerEvent' creates a new event of type 'syntheticEvent' and fires it on 'p1' (what is the primary purpose of this example). The event handler  shows a message without 'p1' being clicked. In other words: The event on 'p1' occurs without a click on 'p1'.

Possibly you need in the event handler some data from the calling function, e.g., the text of an error-message, the data of an HTTP response, ... . You can pass such data by using the  and its property 'detail':

Access the data in the event handle:

(A)synchronous behaviour
Most events are handled synchronously, e.g., 'click', 'key', or 'mouse'. But there are a few exceptions that are handled asynchronously, e.g., 'load'. 'Synchronous' means that the sequence of invocations is the same as the sequence of their creations. Clicking on Button A, B, and then C leads to the invocation of A's, B's, and then C's event handler in exactly this sequence. In contrast, 'asynchronous' events can lead to the invocation of the correlated handlers in an arbitrary sequence.

You must distinguish this question, the invocation of event handlers, from the implementation of their bodies. Every implementation may act strictly sequential or may contain asynchronous calls - it depends on your intention. Typical asynchronous calls are HTTP requests or database queries. Of course, they can be part of the handler of a click event.

Exercises

 * ... are available on another page (click here).