1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
|
---
title: DOM onevent handlers
slug: Web/Guide/Events/Event_handlers
translation_of: Web/Guide/Events/Event_handlers
---
<p>A plataforma web oferece várias maneiras de trabalhar com o <span class="seoSummary"><a href="/en-US/docs/Web/Events">DOM events</a>. </span>Duas abordagens comuns são:<span class="seoSummary"> {{domxref("EventTarget.addEventListener", "addEventListener()")}} e o específico <code>on<em>event</em></code> que dispara um evento.</span> Este artigo se concentra em como o último funciona.</p>
<h2 id="Registering_onevent_handlers">Registering onevent handlers</h2>
<p>The <strong><code>on<em>event</em></code></strong> 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 <code><body></code> element). Events are actions like:</p>
<ul>
<li>Being clicked</li>
<li>Detecting pressed keys</li>
<li>Getting focus</li>
</ul>
<p>The on-event handler is usually named with the event it reacts to, like <code>on<em>click</em></code>, <code>on<em>keypress</em></code>, <code>on<em>focus</em></code>, etc.</p>
<p>You can specify an <code>on<em><…></em></code> event handler for a particular event (such as {{event("click")}}) for a given object in different ways:</p>
<ul>
<li>Adding an HTML {{Glossary("attribute")}} named <code>on<em><eventtype></em></code>:<br>
<code><button <strong>onclick="handleClick()"</strong>></code>,</li>
<li>Or by setting the corresponding {{Glossary("property/JavaScript", "property")}} from JavaScript:<br>
<code>document.querySelector("button")<strong>.onclick = function(event) { … }</strong></code>.</li>
</ul>
<p>An <code>on<em>event</em></code> 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 {{domxref("EventTarget.addEventListener", "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 {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} function.</p>
<p>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 <code>myButton</code>, you can do <code>myButton.onclick(myEventObject)</code> 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 <code>onclick()</code>.</p>
<p>This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling {{domxref("Event.stopPropagation", "stopPropagation()")}} on the event object itself.</p>
<h3 id="Non-element_objects">Non-element objects</h3>
<p>Event handlers can also be set with properties on non-element objects that generate events, like {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others. For example, for the <code>progress</code> event on instances of <code>XMLHttpRequest</code>:</p>
<pre class="brush: js notranslate">const xhr = new XMLHttpRequest();
xhr.onprogress = function() { … };</pre>
<h2 id="HTML_onevent_attributes">HTML onevent attributes</h2>
<p>HTML elements have attributes named <code>on<em>event</em></code> 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 <code>on<em>event</em></code> 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.</p>
<p>Further changes to the HTML attribute value can be done via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute"><code>setAttribute</code> </a>method; Making changes to the JavaScript property will have no effect.</p>
<h3 id="HTML">HTML</h3>
<p>Given this HTML document:</p>
<pre class="brush: html notranslate"><p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
<a onclick="log('Click!')">these three words</a>.
</p>
<div></div></pre>
<h3 id="JavaScript">JavaScript</h3>
<p>Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.</p>
<pre class="brush: js notranslate">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>`);</pre>
<h3 id="Result">Result</h3>
<p>{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}</p>
<p>For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements instead set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onblur">onblur</a></code>, <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onerror">onerror</a></code>, <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onfocus">onfocus</a></code>, <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onload">onload</a></code>, and <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onscroll">onscroll</a></code>.)</p>
<h3 id="Event_handlers_parameters_this_binding_and_the_return_value">Event handler's parameters, <code>this</code> binding, and the return value</h3>
<p>When the event handler is specified as <strong>an HTML attribute</strong>, the specified code is wrapped into a function with <strong>the following parameters</strong>:</p>
<ul>
<li><code>event</code> — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.</li>
<li><code>event</code>, <code>source</code>, <code>lineno</code>, <code>colno</code>, and <code>error</code> for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the <code>event</code> parameter actually contains the error message as a string.</li>
</ul>
<p>When the event handler is invoked, the <code>this</code> keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this#In_an_inline_event_handler">the <code>this</code> keyword documentation</a>.</p>
<p>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 <a href="https://html.spec.whatwg.org/multipage/webappapis.html#the-event-handler-processing-algorithm">"The event handler processing algorithm" in the HTML specification</a>.</p>
<h3 id="When_the_event_handler_is_invoked">When the event handler is invoked</h3>
<div class="blockIndicator note">
<p>TBD (non-capturing listener)</p>
</div>
<h3 id="Terminology">Terminology</h3>
<p>The term <strong>event handler</strong> may refer to:</p>
<ul>
<li>Any function or object that is registered to be notified of events</li>
<li>Or more specifically, to the mechanism of registering event listeners via <code>on…</code> attributes in HTML or properties in Web APIs, such as <code><button onclick="alert(this)"></code> or <code>window.onload = function() { … }</code>.</li>
</ul>
<p>When discussing the various methods of listening to events:</p>
<ul>
<li><strong>Event listener</strong> refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}</li>
<li><strong>Event handler</strong> refers to a function registered via <code>on…</code> attributes or properties</li>
</ul>
<h2 id="Specifications" name="Specifications">Specifications</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}</td>
<td>{{Spec2('HTML WHATWG')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}</td>
<td>{{Spec2('HTML5 W3C')}}</td>
<td></td>
</tr>
</tbody>
</table>
<h2 id="Browser_Compatibility" name="Browser_Compatibility">Browser compatibility</h2>
<h4 id="Detecting_the_presence_of_event_handler_properties">Detecting the presence of event handler properties</h4>
<p>You can detect the presence of an event handler property with the JavaScript <a href="/en-US/JavaScript/Reference/Operators/in" title="en/JavaScript/Reference/Operators/in"><code>in</code></a> operator. For example:</p>
<pre class="brush: js notranslate">if ("onsomenewfeature" in window) {
/* do something amazing */
}
</pre>
<h4 id="Event_handlers_and_prototypes">Event handlers and prototypes</h4>
<p>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 <code>Window.prototype.onload</code>. In the past, event handlers (<code>onload</code>, 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.</p>
|