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
|
---
title: Manejadores de eventos en el DOM
slug: Web/Guide/DOM/Events/eventos_controlador
translation_of: Web/Guide/Events/Event_handlers
---
<p><span class="seoSummary">La plataforma Web provee varias formas de recibir notificaciones de los eventos del <a href="/en-US/docs/Web/Events">DOM</a>. Dos de las formas más comunes son: la general {{domxref("EventTarget.addEventListener", "addEventListener()")}} y un conjunto específico de controladores de eventos específicos.</span> Esta página se enfoca en los detalles de cómo funcionan estos.</p>
<h3 id="Registering_on-event_handlers">Registering <em>on-event</em> handlers</h3>
<p>Los controladores <em><strong>on-event</strong></em> son un grupo de propiedades ofrecidas por los elementos del DOM para ayudar a manejar cómo los elementos reaccionan a los eventos. Los elementos pueden ser interactivos (por ejemplo: enlaces, botones, imagenes, formularios) or non-interactive (e.g. the base document). Los eventos pueden ser cuando se haga un click, detectar cuando se presione una tecla, enfocarse, entre otros. Los handlers on-event son comunmente denominados como el evento al cual deben reaccionar, como ser <code>onclick</code>, <code>onkeypress</code>, <code>onfocus</code>, etc.</p>
<p>Pueden especificar un controlador de evento <code>on<...></code> para un evento en particular (como {{event("click")}}) como un opbjeto determinado de diferentes formas:</p>
<ul>
<li>Usando el HTML {{Glossary("atributo")}} llamados <code>on<em>{eventtype}</em></code> en un elemento, por ejemplo:<br>
<code><button <u>onclick="return handleClick(event);"</u>></code>,</li>
<li>O seteandolo {{Glossary("property/JavaScript", "property")}} desde JavaScript, por ejemplo:<br>
<code>document.getElementById("mybutton")<u>.onclick = function(event) { ... }</u></code>.</li>
</ul>
<p>Un controlador onevent</p>
<p>Notese que cada objeto puede tener sólo un controlador <em>on-event</em> para un evento dado (though that handler could call multiple sub-handlers). This is why {{domxref("EventTarget.addEventListener", "addEventListener()")}} is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.</p>
<p>Also note that <em>on-event</em> handlers are called automatically, not at the programmer's will (although you can, like <code>mybutton.onclick(myevent); ) </code>since they serve more as placeholders to which a real handler function can be <strong>assigned</strong>.</p>
<h3 id="Non-element_objects">Non-element objects</h3>
<p>Event handlers can also be set using properties on many non-element objects that generate events, including {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others, for example:</p>
<pre class="notranslate">xhr.onprogress = function() { ... }</pre>
<h2 id="Details">Details</h2>
<h3 id="The_value_of_HTML_on<...>_attributes_and_corresponding_JavaScript_properties">The value of HTML on<...> attributes and corresponding JavaScript properties</h3>
<p>A handler registered via an <code>on<...></code> attribute will be available via the corresponding <code>on<...></code> property, but not the other way around:</p>
<pre class="brush: html notranslate"><div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
<script>
window.onload = function () {
var div = document.getElementById("a");
console.log("Attribute reflected as a property: ", div.onclick.toString());
// Prints: function onclick(event) { alert('old') }
div.onclick = function() { alert('new') };
console.log("Changed property to: ", div.onclick.toString());
// Prints: function () { alert('new') }
console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
// Prints: alert('old')
}
</script></pre>
<p>For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements actually set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: <code>onblur</code>, <code>onerror</code>, <code>onfocus</code>, <code>onload</code>, <code>onscroll</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 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_in%E2%80%93line_event_handler">the this 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>
<p>TBD (non-capturing listener)</p>
<h3 id="Terminology">Terminology</h3>
<p>The term <strong>event handler</strong> may be used to refer to:</p>
<ul>
<li>any function or object 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>whereas <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>
<h3 id="Event_handler_changes_in_Firefox_9">Event handler changes in Firefox 9</h3>
<p>In order to better match the specifications, and improve cross-browser compatibility, the way event handlers were implemented at a fundamental level changed in Gecko 9.0 {{ geckoRelease("9.0") }}.</p>
<p>Specifically, in the past, event handlers were not correctly implemented as standard IDL attributes. In Gecko 9.0, this was changed. Because of this, certain behaviors of event handlers in Gecko have changed. In particular, they now behave in all the ways standard IDL attributes behave. In most cases, this shouldn't affect web or add-on content at all; however, there are a few specific things to watch out for.</p>
<h4 id="Detecting_the_presence_of_event_handler_properties">Detecting the presence of event handler properties</h4>
<p>You can now detect the presence of an event handler property (that is, for example, <code>onload</code>), using 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> anymore. 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>
|