Event

  • Revision slug: Web/API/Event
  • Revision title: Event
  • Revision id: 453333
  • Created:
  • Creator: teoli
  • Is current revision? No
  • Comment

Revision Content

Introduction

This chapter describes the DOM Event Model. The Event interface itself is described, as well as the interfaces for event registration on nodes in the DOM, and event listeners, and several longer examples that show how the various event interfaces relate to one another.

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

Registering event listeners

There are 3 ways to register event handlers for a DOM element.

EventTarget.addEventListener

// Assuming myButton is a button element
myButton.addEventListener('click', function(){alert('Hello world');}, false);

This is the method you should use in modern web pages.

Note: Internet Explorer 6-8 didn't support this method, offering a similar element.attachEvent API instead. For cross-browser compatibility use one of the many JavaScript libraries available.

More details can be found on the {{domxref("EventTarget.addEventListener")}} reference page.

HTML attribute

<button onclick="alert('Hello world!')">

The JavaScript code in the attribute is passed the Event object via the event parameter. The return value is treated in a special way, described in the HTML specification.

This way should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.

DOM element properties

// Assuming myButton is a button element
myButton.onclick = function(event){alert('Hello world');};

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

The problem with this method is that only one handler can be set per element and per event.

DOM Event interface

Event handlers may be attached to various objects including DOM elements, document, the window object, etc. When an event occurs, an event object is created and passed sequentially to the event listeners.

The DOM Event interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

function foo(evt) {
  // the evt parameter is automatically assigned the event object
  alert(evt);
}
table_el.onclick = foo;

DOM event subclasses

  • {{domxref("AnimationEvent")}}
  • {{domxref("AudioProcessingEvent")}}
  • {{domxref("BeforeUnloadEvent")}}
  • {{domxref("BlobEvent")}}
  • {{domxref("ClipboardEvent")}}
  • {{domxref("CompositionEvent")}}
  • {{domxref("CSSFontFaceLoadEvent")}}
  • {{domxref("CustomEvent")}}
  • {{domxref("DragEvent")}}
  • {{domxref("ErrorEvent")}}
  • {{domxref("FocusEvent")}}
  • {{domxref("HashChangeEvent")}}
  • {{domxref("IDBVersionChangeEvent")}}
  • {{domxref("KeyboardEvent")}}
  • {{domxref("MessageEvent")}}
  • {{domxref("MouseEvent")}}
  • {{domxref("MutationEvent")}}
  • {{domxref("OfflineAudioCompletionEvent")}}
  • {{domxref("PageTransitionEvent")}}
  • {{domxref("PopStateEvent")}}
  • {{domxref("ProgressEvent")}}
  • {{domxref("RelatedEvent")}}
  • {{domxref("SensorEvent")}}
  • {{domxref("StorageEvent")}}
  • {{domxref("SVGEvent")}}
  • {{domxref("SVGZoomEvent")}}
  • {{domxref("TimeEvent")}}
  • {{domxref("TrackEvent")}}
  • {{domxref("TransitionEvent")}}
  • {{domxref("UIEvent")}}
  • {{domxref("WheelEvent")}}

Properties

{{domxref("event.bubbles")}}
A boolean indicating whether the event bubbles up through the DOM or not.
{{domxref("event.cancelBubble")}} {{Deprecated_inline}}
A boolean indicating whether the bubbling of the event has been canceled or not.
{{domxref("event.cancelable")}}
A boolean indicating whether the event is cancelable.
{{domxref("event.currentTarget")}}
A reference to the currently registered target for the event.
{{domxref("event.defaultPrevented")}}
Indicates whether or not {{domxref("event.preventDefault()")}} has been called on the event.
{{domxref("event.eventPhase")}}
Indicates which phase of the event flow is being processed.
{{domxref("event.explicitOriginalTarget")}} {{non-standard_inline}}
The explicit original target of the event (Mozilla-specific).
{{domxref("event.originalTarget")}} {{non-standard_inline}}
The original target of the event, before any retargetings (Mozilla-specific).
{{domxref("event.target")}}
A reference to the target to which the event was originally dispatched.
{{domxref("event.timeStamp")}}
The time that the event was created.
{{domxref("event.type")}}
The name of the event (case-insensitive).
{{domxref("event.isTrusted")}}
Indicates whether or not the event was initiated by the browser (after a user click for instance) or by a script (using an event creation method, like event.initEvent)

Methods

{{domxref("event.initEvent")}}
Initializes the value of an Event created through the DocumentEvent interface.
{{domxref("event.preventBubble")}} {{Obsolete_inline(24)}}
Prevents the event from bubbling. Obsolete, use {{domxref("event.stopPropagation")}} instead.
{{domxref("event.preventCapture")}} {{Obsolete_inline(24)}}
Obsolete, use {{domxref("event.stopPropagation")}} instead.
{{domxref("event.preventDefault")}}
Cancels the event (if it is cancelable).
{{domxref("event.stopImmediatePropagation")}}
For this particular event, no other listener will be called. Neither those attached on the same element, nor those attached on elements which will be traversed later (in capture phase, for instance)
{{domxref("event.stopPropagation")}}
Stops the propagation of events further along in the DOM.

See also

Revision Source

<h2 id="Introduction" name="Introduction">Introduction</h2>
<p>This chapter describes the DOM Event Model. The <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event">Event</a> interface itself is described, as well as the interfaces for event registration on nodes in the DOM, and <a href="/en-US/docs/Web/API/EventTarget.addEventListener">event listeners</a>, and several longer examples that show how the various event interfaces relate to one another.</p>
<p>There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the <a href="http://www.w3.org/TR/DOM-Level-3-Events/#dom-event-architecture">DOM Level 3 Events draft</a>.</p>
<p>Also see <a href="/en-US/docs/DOM/DOM_Reference/Examples#Example_5:_Event_Propagation">Example 5: Event Propagation</a> in the Examples chapter for a more detailed example of how events move through the DOM.</p>
<h2 id="DOM_event_handler_List" name="DOM_event_handler_List">Registering event listeners</h2>
<p>There are 3 ways to register event handlers for a DOM element.</p>
<h3 id="EventTarget.addEventListener" name="EventTarget.addEventListener"><a href="/en-US/docs/Web/API/EventTarget.addEventListener"><code>EventTarget.addEventListener</code></a></h3>
<pre class="brush: js">
// Assuming myButton is a button element
myButton.addEventListener('click', function(){alert('Hello world');}, false);
</pre>
<p>This is the method you should use in modern web pages.</p>
<p>Note: Internet Explorer 6-8 didn't support this method, offering a similar <code>element.attachEvent</code> API instead. For cross-browser compatibility use one of the many JavaScript libraries available.</p>
<p>More details can be found on the {{domxref("EventTarget.addEventListener")}} reference page.</p>
<h3 id="HTML_attribute" name="HTML_attribute">HTML attribute</h3>
<pre class="brush: html">
&lt;button onclick="alert('Hello world!')"&gt;
</pre>
<p>The JavaScript code in the attribute is passed the Event object via the <code>event</code> parameter. <a href="http://dev.w3.org/html5/spec/webappapis.html#the-event-handler-processing-algorithm">The return value is treated in a special way, described in the HTML specification</a>.</p>
<p>This way should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.</p>
<h3 id="DOM_element_properties" name="DOM_element_properties">DOM element properties</h3>
<pre class="brush: js">
// Assuming myButton is a button element
myButton.onclick = function(event){alert('Hello world');};
</pre>
<p>The function can be defined to take an <code>event</code> parameter. <a href="http://dev.w3.org/html5/spec/webappapis.html#the-event-handler-processing-algorithm">The return value is treated in a special way, described in the HTML specification</a>.</p>
<p>The problem with this method is that only one handler can be set per element and per event.</p>
<h2 id="DOM_Event_interface" name="DOM_Event_interface">DOM <code>Event</code> interface</h2>
<p>Event handlers may be attached to various objects including DOM elements, document, the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">window object</a>, etc. When an event occurs, an event object is created and passed sequentially to the event listeners.</p>
<p>The DOM <code>Event</code> interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.</p>
<pre class="brush: js">
function foo(evt) {
  // the evt parameter is automatically assigned the event object
  alert(evt);
}
table_el.onclick = foo;
</pre>
<h3 id="DOM_event_subclasses" name="DOM_event_subclasses">DOM event subclasses</h3>
<div class="index">
  <ul>
    <li>{{domxref("AnimationEvent")}}</li>
    <li>{{domxref("AudioProcessingEvent")}}</li>
    <li>{{domxref("BeforeUnloadEvent")}}</li>
    <li>{{domxref("BlobEvent")}}</li>
    <li>{{domxref("ClipboardEvent")}}</li>
    <li>{{domxref("CompositionEvent")}}</li>
    <li>{{domxref("CSSFontFaceLoadEvent")}}</li>
    <li>{{domxref("CustomEvent")}}</li>
    <li>{{domxref("DragEvent")}}</li>
    <li>{{domxref("ErrorEvent")}}</li>
    <li>{{domxref("FocusEvent")}}</li>
    <li>{{domxref("HashChangeEvent")}}</li>
    <li>{{domxref("IDBVersionChangeEvent")}}</li>
    <li>{{domxref("KeyboardEvent")}}</li>
    <li>{{domxref("MessageEvent")}}</li>
    <li>{{domxref("MouseEvent")}}</li>
    <li>{{domxref("MutationEvent")}}</li>
    <li>{{domxref("OfflineAudioCompletionEvent")}}</li>
    <li>{{domxref("PageTransitionEvent")}}</li>
    <li>{{domxref("PopStateEvent")}}</li>
    <li>{{domxref("ProgressEvent")}}</li>
    <li>{{domxref("RelatedEvent")}}</li>
    <li>{{domxref("SensorEvent")}}</li>
    <li>{{domxref("StorageEvent")}}</li>
    <li>{{domxref("SVGEvent")}}</li>
    <li>{{domxref("SVGZoomEvent")}}</li>
    <li>{{domxref("TimeEvent")}}</li>
    <li>{{domxref("TrackEvent")}}</li>
    <li>{{domxref("TransitionEvent")}}</li>
    <li>{{domxref("UIEvent")}}</li>
    <li>{{domxref("WheelEvent")}}</li>
  </ul>
</div>
<h3 id="Properties" name="Properties">Properties</h3>
<dl>
  <dt>
    {{domxref("event.bubbles")}}</dt>
  <dd>
    A boolean indicating whether the event bubbles up through the DOM or not.</dd>
  <dt>
    {{domxref("event.cancelBubble")}} {{Deprecated_inline}}</dt>
  <dd>
    A boolean indicating whether the bubbling of the event has been canceled or not.</dd>
  <dt>
    {{domxref("event.cancelable")}}</dt>
  <dd>
    A boolean indicating whether the event is cancelable.</dd>
  <dt>
    {{domxref("event.currentTarget")}}</dt>
  <dd>
    A reference to the currently registered target for the event.</dd>
  <dt>
    {{domxref("event.defaultPrevented")}}</dt>
  <dd>
    Indicates whether or not {{domxref("event.preventDefault()")}} has been called on the event.</dd>
  <dt>
    {{domxref("event.eventPhase")}}</dt>
  <dd>
    Indicates which phase of the event flow is being processed.</dd>
  <dt>
    {{domxref("event.explicitOriginalTarget")}} {{non-standard_inline}}</dt>
  <dd>
    The explicit original target of the event (Mozilla-specific).</dd>
  <dt>
    {{domxref("event.originalTarget")}} {{non-standard_inline}}</dt>
  <dd>
    The original target of the event, before any retargetings (Mozilla-specific).</dd>
  <dt>
    {{domxref("event.target")}}</dt>
  <dd>
    A reference to the target to which the event was originally dispatched.</dd>
  <dt>
    {{domxref("event.timeStamp")}}</dt>
  <dd>
    The time that the event was created.</dd>
  <dt>
    {{domxref("event.type")}}</dt>
  <dd>
    The name of the event (case-insensitive).</dd>
  <dt>
    {{domxref("event.isTrusted")}}</dt>
  <dd>
    Indicates whether or not the event was initiated by the browser (after a user click for instance) or by a script (using an event creation method, like <a href="/en-US/docs/DOM/event.initEvent">event.initEvent</a>)</dd>
</dl>
<h3 id="Methods" name="Methods">Methods</h3>
<dl>
  <dt>
    {{domxref("event.initEvent")}}</dt>
  <dd>
    Initializes the value of an Event created through the <code>DocumentEvent</code> interface.</dd>
  <dt>
    {{domxref("event.preventBubble")}} {{Obsolete_inline(24)}}</dt>
  <dd>
    Prevents the event from bubbling. Obsolete, use {{domxref("event.stopPropagation")}} instead.</dd>
  <dt>
    {{domxref("event.preventCapture")}} {{Obsolete_inline(24)}}</dt>
  <dd>
    Obsolete, use {{domxref("event.stopPropagation")}} instead.</dd>
  <dt>
    {{domxref("event.preventDefault")}}</dt>
  <dd>
    Cancels the event (if it is cancelable).</dd>
  <dt>
    {{domxref("event.stopImmediatePropagation")}}</dt>
  <dd>
    For this particular event, no other listener will be called. Neither those attached on the same element, nor those attached on elements which will be traversed later (in capture phase, for instance)</dd>
  <dt>
    {{domxref("event.stopPropagation")}}</dt>
  <dd>
    Stops the propagation of events further along in the DOM.</dd>
</dl>
<h2 id="See_also" name="See_also">See also</h2>
<ul>
  <li>Types of events available: <a href="/en-US/docs/Web/Reference/Events">Event reference</a></li>
  <li><a href="/en-US/docs/Web/API/Event/Comparison_of_Event_Targets">Comparison of Event Targets</a> (target vs currentTarget vs relatedTarget vs originalTarget)</li>
  <li><a href="/en-US/docs/Web/Guide/DOM/Events/Creating_and_triggering_events">Creating and triggering custom events</a></li>
  <li>For Firefox add-on developers:
    <ul>
      <li><a href="/en-US/docs/Listening_to_events_in_Firefox_extensions">Listening to events in Firefox extensions</a></li>
      <li><a href="/en-US/docs/Listening_to_events_on_all_tabs">Listening to events on all tabs</a></li>
    </ul>
  </li>
  <li><a class="link-https" href="https://wiki.mozilla.org/Events">Mozilla related events in real life at wiki.mozilla.org</a></li>
</ul>
Revert to this revision