DOM onevent handlers

The Web platform provides several ways to be notified of DOM events. Two common approaches are addEventListener() and the specific onevent handlers. This page focuses on how the latter work.

Registering onevent handlers

The onevent handlers are properties on certain DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and so forth) or non-interactive (such as the base <body> element). Events are actions like:

  • Being clicked
  • Detecting pressed keys
  • Getting focus

The on-event handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc.

You can specify an on<…> event handler for a particular event (such as click) for a given object in different ways:

  • Adding an HTML attribute named on<eventtype>:
    <button onclick="handleClick">,
  • Or by setting the corresponding property from JavaScript:
    document.querySelector("button").onclick = function(event) { … }.

An onevent event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. In order to allow multiple handlers to be installed for the same event on a given object, you can call its addEventListener() method, which manages a list of handlers for the given event on the object. A handler can then be removed from the object by calling its removeEventListener() function.

When an event occurs that applies to an element, each of its event handlers is called to allow them to handle the event, one after another. You don't need to call them yourself, although you can do so in many cases to easily simulate an event taking place. For example, given a button object myButton, you can do myButton.onclick(myEventObject) to call the event handler directly. If the event handler doesn't access any data form the event object, you can leave out the event when calling onclick().

This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling stopPropagation() on the event object itself.

Non-element objects

Event handlers can also be set with properties on non-element objects that generate events, like window, document, XMLHttpRequest, and others. For example, for the progress event on instances of XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.onprogress = function() { … };

HTML onevent attributes

HTML elements have attributes named onevent which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its onevent attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using JavaScript will get the value set in the HTML.

However, this is a one-time thing. From that point on, making changes to the JavaScript property has no effect on the HTML attribute's value:

HTML

Given this HTML document:

<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
   <span onclick="log('Click!')">these three words</a>.</p>

<div></div>

JavaScript

Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.

var logElement = document.querySelector("div");
var log = msg => logElement.innerHTML += `${msg}<br>`;

let el = document.querySelector("span");

// This will print the value as <code>function onclick(event) { log('Click!') }</code>
log("Element's onclick as a JavaScript property: ", el.onclick);

el.onclick = function() { log("Called the changed the onclick handler!") };
log(`Changed the property to: <code>${el.click}</code>`);

log(`But the HTML attribute is unchanged: <code>${el.getAttribute("onclick")}</code>`);

Result

For historical reasons, some attributes/properties on the <body> and <frameset> elements instead set event handlers on their parent Window object. (The HTML specification names these: onblur, onerror, onfocus, onload, and onscroll.)

Event handler's parameters, this binding, and the return value

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

  • event — for all event handlers except onerror.
  • event, source, lineno, colno, and error for the onerror event handler. Note that the event parameter actually contains the error message as a string.

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see "The event handler processing algorithm" in the HTML specification.

When the event handler is invoked

TBD (non-capturing listener)

Terminology

The term event handler may refer to:

  • Any function or object that is registered to be notified of events
  • Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { … }.

When discussing the various methods of listening to events:

  • Event listener refers to a function or object registered via EventTarget.addEventListener()
  • Event handler refers to a function registered via on… attributes or properties

Specifications

Specification Status Comment
HTML Living Standard
The definition of 'event handlers' in that specification.
Living Standard
HTML5
The definition of 'event handlers' in that specification.
Recommendation

Browser compatibility

Detecting the presence of event handler properties

You can detect the presence of an event handler property with the JavaScript in operator. For example:

if ("onsomenewfeature" in window) {
  /* do something amazing */
}

Event handlers and prototypes

You can't set or access the values of any IDL-defined attributes on DOM prototype objects. That means you can't, for example, change Window.prototype.onload. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.