Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1026304 of DOM on-event handlers

  • Revision slug: Web/Guide/Events/Event_handlers
  • Revision title: DOM on-event handlers
  • Revision id: 1026304
  • Created:
  • Creator: rolfedh
  • Is current revision? No
  • Comment Editorial review. Minor edits.

Revision Content

Summary

The Web platform provides several ways to get notified of DOM events.  Three common styles are: The generalized {{domxref("EventTarget.addEventListener", "addEventListener()")}}, single-purpose utilities like {{domxref("WindowTimers.setTimeout", "setTimeout()")}},  and a set of specific on-event handlers. This page focuses on the details of how the latter work.

Registering on-event handlers

The on-event handlers are a group of properties offered by interactive DOM elements such as links, buttons, images, forms, the base document itself, and so on, to help manage how that element reacts to events like being clicked, detecting pressed keys, getting focus, etc. -- and they are usually named accordingly, such as onclick, onkeypress, onfocus, etc. You can specify an on<...> event handler for a particular event (such as {{event("click")}}) for a given object in different ways:

  • Using an HTML {{Glossary("attribute")}} named on{eventtype} on an element, for example:
    <button onclick="return handleClick(event);">,
  • Or by setting the corresponding {{Glossary("property/JavaScript", "property")}} from JavaScript, for example:
    document.getElementById("mybutton").onclick = function(event) { ... }.

Note that each object can have only one on-event handler for a given event (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.

Non-element objects

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() { ... }

Details

The value of HTML on<...> attributes and corresponding  JavaScript properties

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.)

Event handler's parameters, this binding, and the return value

TBD

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 {{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

TBD (non-capturing listener)

Terminology

The term event handler may be used to refer to:

  • any function or object 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 {{domxref("EventTarget.addEventListener()")}},
  • whereas event handler refers to a function registered via on... attributes or properties.

Specifications

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')}}  

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}

Event handler changes in Firefox 9

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.

Detecting the presence of event handler properties

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 */
}

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

Revision Source

<h2 id="Summary">Summary</h2>

<p>The Web platform provides several ways to get notified of <a href="/en-US/docs/Web/Events">DOM events</a>. &nbsp;Three&nbsp;common&nbsp;styles are: The generalized {{domxref("EventTarget.addEventListener", "addEventListener()")}}, single-purpose utilities like {{domxref("WindowTimers.setTimeout", "setTimeout()")}}, &nbsp;and a set of specific&nbsp;<em><strong>on-event</strong></em> handlers. This page focuses on the details of how the latter work.</p>

<h3 id="Registering_on-event_handlers">Registering <em>on-event</em> handlers</h3>

<p>The <em><strong>on-event</strong></em> handlers are a group of properties offered by interactive DOM elements such as links, buttons, images, forms, the base document itself, and so on, to help manage how that element reacts to events like being clicked, detecting pressed keys, getting focus, etc. -- and they are usually named accordingly, such as<code>&nbsp;onclick</code>, <code>onkeypress</code>, <code>onfocus</code>, etc. You can specify an <code>on&lt;...&gt;</code> event handler for a particular event (such as {{event("click")}}) for a given object in different&nbsp;ways:</p>

<ul>
 <li>Using an HTML {{Glossary("attribute")}} named <code>on<em>{eventtype}</em></code> on an element, for example:<br />
  <code>&lt;button <u>onclick="return handleClick(event);"</u>&gt;</code>,</li>
 <li>Or by setting the corresponding {{Glossary("property/JavaScript", "property")}} from JavaScript, for example:<br />
  <code>document.getElementById("mybutton")<u>.onclick = function(event) { ... }</u></code>.</li>
</ul>

<p>Note that each object can have <strong>only one</strong> <em>on-event</em> handler for a given event (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. &nbsp;Also note that <em>on-event</em> handlers are called automatically, not at the programmer's will (although you can, like &nbsp;<code>mybutton.onclick(myevent); )&nbsp;</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>
xhr.onprogress = function() { ... }</pre>

<h2 id="Details">Details</h2>

<h3 id="The_value_of_HTML_on&lt;...&gt;_attributes_and_corresponding_JavaScript_properties">The value of HTML on&lt;...&gt; attributes and corresponding&nbsp; JavaScript properties</h3>

<p>A handler registered via an <code>on&lt;...&gt;</code> attribute will be available via the corresponding <code>on&lt;...&gt;</code> property, but not the other way around:</p>

<pre class="brush: html">
&lt;div id="a" onclick="alert('old')"&gt;Open the Developer Tools Console to see the output.&lt;/div&gt;

&lt;script&gt;
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')
}
&lt;/script&gt;</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_handler's_parameters_this_binding_and_the_return_value">Event handler's parameters, <code>this</code> binding, and the return value</h3>

<p>TBD</p>

<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>

<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>&lt;button onclick="alert(this)"&gt;</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>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}</td>
   <td>{{Spec2('HTML5 W3C')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_Compatibility" name="Browser_Compatibility">Browser compatibility</h2>

<p>{{ CompatibilityTable() }}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
  </tr>
 </tbody>
</table>
</div>

<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/JavaScript/Reference/Operators/in" title="en/JavaScript/Reference/Operators/in"><code>in</code></a> operator. For example:</p>

<pre class="brush: js">
if ("onsomenewfeature" in window) {
&nbsp; /* 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>
Revert to this revision