DOM onevent handlers - Developer guides 编辑
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.
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 Handler
log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);
//Changing handler using .onclick
log('<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 .setAttribute
log('<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 exceptonerror
.event
,source
,lineno
,colno
, anderror
for theonerror
event handler. Note that theevent
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)">
orwindow.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论