DOM onevent handlers - Developer guides (2024)

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 onevent 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 from 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.

Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.

See Also
AOT Overview

HTML

Given this HTML document:

<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on <a 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.

let logElement = document.querySelector('div');let el = document.querySelector("a");function log(msg) { logElement.innerHTML += `${msg}<br>` };function anchorOnClick(event) { log("Changed onclick handler") };// Original Handlerlog(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);//Changing handler using .onclicklog('<br>Changing onclick handler using <strong> onclick property </strong> ');el.onclick = anchorOnClick;log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`);//Changing handler using .setAttributelog('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> ');el.setAttribute("onclick", 'anchorOnClick(event)');log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);

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.

DOM onevent handlers - Developer guides (2024)
Top Articles
Why this College Essay ~ How to Write It
24 Main Advantages & Disadvantages of Technology in 21st Century
My Arkansas Copa
Baseball-Reference Com
Clairememory Scam
Crusader Kings 3 Workshop
Bad Moms 123Movies
iOS 18 Hadir, Tapi Mana Fitur AI Apple?
Grab this ice cream maker while it's discounted in Walmart's sale | Digital Trends
Puretalkusa.com/Amac
Voy Boards Miss America
Byui Calendar Fall 2023
Jalapeno Grill Ponca City Menu
Hollywood Bowl Section H
Td Small Business Banking Login
Www.publicsurplus.com Motor Pool
Indystar Obits
The Ultimate Guide to Extras Casting: Everything You Need to Know - MyCastingFile
Aerocareusa Hmebillpay Com
Titanic Soap2Day
The Old Way Showtimes Near Regency Theatres Granada Hills
Jail View Sumter
Greyson Alexander Thorn
Panolian Batesville Ms Obituaries 2022
Watson 853 White Oval
Martins Point Patient Portal
Die wichtigsten E-Nummern
Ilabs Ucsf
Workboy Kennel
Phone number detective
Omnistorm Necro Diablo 4
Jefferson Parish Dump Wall Blvd
Imperialism Flocabulary Quiz Answers
Dr Adj Redist Cadv Prin Amex Charge
5 Tips To Throw A Fun Halloween Party For Adults
Section 212 at MetLife Stadium
Infinite Campus Parent Portal Hall County
Dee Dee Blanchard Crime Scene Photos
Craigslist en Santa Cruz, California: Tu Guía Definitiva para Comprar, Vender e Intercambiar - First Republic Craigslist
Discover Things To Do In Lubbock
Below Five Store Near Me
Locate phone number
Mathews Vertix Mod Chart
Guided Practice Activities 5B-1 Answers
Iman Fashion Clearance
Accident On 40 East Today
Bonecrusher Upgrade Rs3
Craigslist Pet Phoenix
1Tamilmv.kids
Grace Charis Shagmag
Shad Base Elevator
Latest Posts
Article information

Author: Horacio Brakus JD

Last Updated:

Views: 6867

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Horacio Brakus JD

Birthday: 1999-08-21

Address: Apt. 524 43384 Minnie Prairie, South Edda, MA 62804

Phone: +5931039998219

Job: Sales Strategist

Hobby: Sculling, Kitesurfing, Orienteering, Painting, Computer programming, Creative writing, Scuba diving

Introduction: My name is Horacio Brakus JD, I am a lively, splendid, jolly, vivacious, vast, cheerful, agreeable person who loves writing and wants to share my knowledge and understanding with you.