--- title: Manejadores de eventos en el DOM slug: Web/Guide/Events/Event_handlers translation_of: Web/Guide/Events/Event_handlers original_slug: Web/Guide/DOM/Events/eventos_controlador ---
La plataforma Web provee varias formas de recibir notificaciones de los eventos del DOM. 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. Esta página se enfoca en los detalles de cómo funcionan estos.
Los controladores on-event 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 onclick
, onkeypress
, onfocus
, etc.
Pueden especificar un controlador de evento on<...>
para un evento en particular (como {{event("click")}}) como un opbjeto determinado de diferentes formas:
on{eventtype}
en un elemento, por ejemplo:<button onclick="return handleClick(event);">
,document.getElementById("mybutton").onclick = function(event) { ... }
.Un controlador onevent
Notese que cada objeto puede tener sólo un controlador on-event 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.
Also note that on-event handlers are called automatically, not at the programmer's will (although you can, like mybutton.onclick(myevent); )
since they serve more as placeholders to which a real handler function can be assigned.
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:
xhr.onprogress = function() { ... }
A handler registered via an on<...>
attribute will be available via the corresponding on<...>
property, but not the other way around:
<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>
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: onblur
, onerror
, onfocus
, onload
, onscroll
.)
this
binding, and the return valueWhen 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 {{domxref("GlobalEventHandlers.onerror", "onerror")}}.event
, source
, lineno
, colno
, and error
for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event
parameter actually contains the error message as 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.
TBD (non-capturing listener)
The term event handler may be used to refer to:
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,
on...
attributes or properties.Specification | Status | Comment |
---|---|---|
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}} | {{Spec2('HTML WHATWG')}} | |
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}} | {{Spec2('HTML5 W3C')}} |
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") }}.
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.
You can now detect the presence of an event handler property (that is, for example, onload
), using the JavaScript in
operator. For example:
if ("onsomenewfeature" in window) { /* do something amazing */ }
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
anymore. 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.