Search

The Online Encyclopedia and Dictionary

 
     
 

Encyclopedia

Dictionary

Quotes

 

DOM Events

DOM Events allow event-driven programming languages like JavaScript, JScript, ECMAScript, VBScript and Java to register various event handlers/listeners on the element nodes inside a DOM tree, e.g. HTML, XHTML, XUL and SVG documents.

Historically, like DOM, the event models used by various web browsers had some significant differences. This caused incompatibity problems. Fortunately the event model was standardized by the W3C in DOM Level 2.

Contents

Events

HTML events

Common/W3C events

There is a huge collection of events that can be registered to most element nodes:

  • Mouse events
  • Keyboard events
  • HTML frame/object events
  • HTML form events
  • Use interface events
  • Mutation events (notification of any changes to the structure of a document)

Note that the event classification above is not exactly the same as W3C's classification.

Category Type Attribute Description Bubbles Cancelable
Mouse click onclick Fires when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is:
  • mousedown
  • mouseup
  • click
Yes Yes
dblclick ondblclick Fires when the pointing device button is double clicked over an element. Yes Yes
mousedown onmousedown Fires when the pointing device button is pressed over an element. Yes Yes
mouseup onmouseup Fires when the pointing device button is released over an element. Yes Yes
mouseover onmouseover Fires when the pointing device button is moved onto an element. Yes Yes
mousemove onmousemove Fires when the pointing device button is moved while it is over an element. Yes No
mouseout onmouseout Fires when the pointing device button is moved away from an element. Yes Yes
Keyboard keypress onkeypress Fires when a key on the keyboard is "clicked". A keyress is defined as a keydown and keyup on the same key. The sequence of these events is:
  • keydown
  • keyup
  • keypress
Yes Yes
keydown onkeydown Fires when a key on the keyboard is pressed. Yes Yes
keyup onkeyup Fires when a key on the keyboard is released. Yes Yes
HTML frame/object load onload Fires when finishes loading all content within a document, including window, frame, object and image. No No
unload onunload Fires when removes all content from a window or frame. No No
abort onabort Fires when an object/image loading is stopped before completely loaded. Yes No
error onerror Fires when an object/image/frame cannot be loaded properly. Yes No
resize onresize Fires when a document view is resized. Yes No
scroll onscroll Fires when a document view is scrolled. Yes No
HTML form select onselect Fires when a user selects some text in a text field, including input and textarea. Yes No
change onchange Fires when a control loses the input focus and its value has been modified since gaining focus, including input, select and textarea. Yes No
submit onsubmit Fires when a form is submitted. Yes Yes
reset onreset Fires when a form is reset. Yes No
focus onfocus Fires when an element receives focus either via the pointing device or by tabbing navigation, including label, input, select, textarea, and button. No No
blur onblur Fires when an element loses focus either via the pointing device or by tabbing navigation, including label, input, select, textarea, and button. No No
User interface DOMFocusIn ondomfocusin Similar to HTML focus event, but can be applied to any focusable element. Yes No
DOMFocusOut ondomfocusout Similar to HTML blur event, but can be applied to any focusable element. Yes No
DOMActivate ondomactivate Similar to XUL command event. Fires when an element is activated, for instance, through a mouse click or a keypress. Yes Yes
Mutation DOMSubtreeModified onsubtreemodified Fire when the subtree is modified. Yes No
DOMNodeInserted onnodeinserted Fires when a node has been added as a child of another node. Yes No
DOMNodeRemoved onnoderemoved Fires when a node is being removed from its parent node. Yes No
DOMNodeRemovedFromDocument onnoderemovedfromdocument Fires when a node is being removed from a document. No No
DOMNodeInsertedIntoDocument onnodeinsertedintodocument Fires when a node is being inserted into a document. No No
DOMAttrModified onattrmodified Fires when an attribute has been modified. Yes No
DOMCharacterDataModified oncharacterdatamodified Fires when the character data has been modified. Yes No

Note that the DOM* events are currently not supported by any browser, except Mozilla which supports DOMAttrModified, DOMNodeInserted and DOMNodeRemoved.

Microsoft-specific events

Two major types of events are added by Microsoft. Programmers should try to avoid using them as these can only be used in Internet Explorer:

Category Type Attribute Description Bubbles Cancelable
Clipboard cut oncut Fires a selection is cut to the clipboard.  ?  ?
copy oncopy Fires a selection is copied to the clipboard.  ?  ?
paste oncut Fires a selection is pasted to the clipboard.  ?  ?
beforecut onbeforecut Fires before a selection is cut to the clipboard.  ?  ?
beforecopy onbeforecopy Fires before a selection is copied to the clipboard.  ?  ?
beforspaste onbeforspaste Fires before a selection is pasted to the clipboard.  ?  ?
Data binding afterupdate onafterupdate Fires immediately after a databound object has been updated.  ?  ?
beforeupdate onbeforeupdate Fires before a data source is updated.  ?  ?
cellchange oncellchange Fires when a data source has changed.  ?  ?
dataavailable ondataavailable Fires when new data from a data source become available.  ?  ?
datasetchange ondatasetchange Fires when content at a data source has changed.  ?  ?
datasetcomplete ondatasetcomplete Fires when transfer of data from the data source has completed.  ?  ?
errorupdate onerrorupdate Fires if an error occurs while updating a data field.  ?  ?
rowenter onrowenter Fires when a new row of data from the data source is available.  ?  ?
rowexit onrowexit Fires when a row of data from the data source has just finished.  ?  ?
rowdelete onrowdelete Fires when a row of data from the data source is deleted.  ?  ?
rowinserted onrowinserted Fires when a row of data from the data source is inserted.  ?  ?
Mouse contextmenu oncontextmenu Fires when the context menu is shown.  ?  ?
drag ondrag Fires when during a mouse drag.  ?  ?
dragstart ondragstart Fires when a mouse drag begins.  ?  ?
dragenter ondragenter Fires when something is dragged onto an area.  ?  ?
dragover ondragover Fires when a drag is held over an area.  ?  ?
dragleave ondragleave Fires when something is dragged out of an area.  ?  ?
dragend ondragend Fires when a mouse drag ends.  ?  ?
drop ondrop Fires when a mouse button is released over a valid target during a drag.  ?  ?
Keyboard help onhelp Fires when the user initiates help.  ?  ?
HTML frame/object beforeunload onbeforeunload Fires before a document is unloaded.  ?  ?
stop onstop Fires when the user stops loading the object. (Same as abort event?)  ?  ?
HTML form selectstart onselectstart Fires when the object is selected.  ?  ?
beforeeditfocus onbeforeeditfocus Fires before an element gains focus for editing.  ?  ?
Marquee start onstart Fires when a marquee begins a new loop.  ?  ?
end onend Fires when a marquee finishes its scrolling.  ?  ?
bounce onbounce Fires when a scrolling marquee bounces back in the other direction.  ?  ?
Miscellaneous beforeprint onbeforeprint Fires before a document is printed  ?  ?
afterprint onafterprint Fires immediately after the document prints.  ?  ?
propertychange onpropertychange Fires when the property of an object is changed.  ?  ?
filterchange onfilterchange Fires when a filter changes properties or finishes a transition.  ?  ?
readystatechange onreadystatechange Fires when the readyState property of an element changes.  ?  ?
lostcapture onlostcapture Fires when the releaseCapture method is invoked.  ?  ?

Note that Mozilla, Safari and Opera also support readystatechange event for the XMLHttpRequest object. Mozilla also supports the beforeunload event using traditional event registration method (DOM Level 0).

XUL events

In addition to the common/W3C events, Mozilla defined a set of events that work only with XUL elements.

Category Type Attribute Description Bubbles Cancelable
Mouse DOMMouseScroll DOMMouseScroll Fires when the mouse wheel is moved, causing the content to scroll. No No
dragdrop ondragdrop Fires when the user releases the mouse button to drop an object being dragged. No No
dragenter ondragenter Fires when the mouse pointer moves away from an element during a drag. No No
draggesture ondraggesture Fires when the user starts dragging the element, usually by holding down the mouse button and moving the mouse. No No
dragover ondragover Related to the mousemove event, this event is fired while something is being dragged over an element. No No
Input CheckboxStateChange Fires when a checkbox is checked or unchecked, either by the user or a script. No No
RadioStateChange Fires when a radio button is selected, either by the user or a script. No No
close onclose Fires when a request has been made to close the window. No Yes
command oncommand Similar to W3C DOMActivate event. Fires when an element is activated, for instance, through a mouse click or a keypress. No No
input oninput Fires when a user enters text in a textbox. No No
User interface DOMMenuItemActive DOMMenuItemActive Fires when a menu or menuitem is hovered over, or highlighted. Yes No
DOMMenuItemInactive DOMMenuItemInactive Fires when a menu or menuitem is no longer being hovered over, or highlighted. Yes No
contextmenu oncontextmenu Fires when the user requests to open the context menu for the element. The action to do this varies by platform, but it will typically be a right click. No Yes
overflow onoverflow Fires a box or other layout element when there is not enough space to display it at full size. No No
overflowchanged onoverflowchanged Fires when the overflow state changes. No No
underflow onunderflow Fires to an element when there becomes enough space to display it at full size. No No
popuphidden onpopuphidden Fires to a popup after it has been hidden. No No
popuphiding onpopuphiding Fires to a popup when it is about to be hidden. No No
popupshowing onpopupshowing Fires to a popup just before it is popped open. No Yes
popupshown onpopupshown Fires to a popup after it has been opened, much like the onload event is sent to a window when it is opened. No No
Command broadcast onbroadcast Placed on an observer. The broadcast event is sent when the attributes of the broadcaster being listened to are changed. No No
commandupdate oncommandupdate Fires when a command update occurs. No No

There is also an undocumented event known as "DOMContentLoaded", which fires when the DOM content is loaded. This is different from "load" as it fires before the loading of related files (e.g. image).

Event flow

Considering the situtation when there are 2 elements nested together. Both have event handlers registered on the same event type, say click. When the user clicks on the inner element, there are two possible ways to handle it:

  • Trigger the elements from outer to inner (event capturing). This model is implemented in Netscape Navigator.
  • Trigger the elements from inner to outer (event bubbling). This model is implemented in Internet Explorer and other browsers.

W3C takes a middle position in this struggle. Events are first captured until it reaches the target element, and then bubbled up. During the event flow, an event can be responded to at any element in the path (an observer) in either phase by causing an action, and/or by stopping the event, and/or by cancelling the default action for the event.

Event object

The Event object provides a lots of information about a particular event, including information about target element, key pressed, mouse button pressed, mouse position, etc. Unfortunately, there are very serious browser incompatibilities in this area. Hence only the W3C Event object is discussed in this article.

Event properties
Type Name Description
DOMString type The name of the event (case-insensitive).
EventTarget target Used to indicate the EventTarget to which the event was originally dispatched.
EventTarget currentTarget Used to indicate the EventTarget whose EventListeners are currently being processed.
unsigned short eventPhase Used to indicate which phase of event flow is currently being evaluated.
boolean bubbles Used to indicate whether or not an event is a bubbling event.
boolean cancelable Used to indicate whether or not an event can have its default action prevented.
DOMTimeStamp timeStamp Used to specify the time (in milliseconds relative to the epoch) at which the event was created.
Event methods
Name Argument type Argument name Description
stopPropagation To prevent further propagation of an event during event flow.
preventDefault To cancel the event if it is cancalable, meaning that any default action normally taken by the implementation as a result of the event will not occur.
initEvent DOMString eventTypeArg Specifies the event type.
boolean canBubbleArg Specifies whether or not the event can bubble.
boolean cancelableArg Specifies whether or not the event's default action can be prevented.

Event handling models

DOM Level 0

This event handling model was introduced by Netscape Navigator, and remains the most cross-browser model as of 2005. There are 2 types of model: inline model and traditional model.

Inline model

In the inline model, event handlers are added as attribute of element. Each event can be only one event handler registered. There is no way to remove the event handler from an element:


<head>
  <script type="text/javascript">
    function helloWorld( name )
    {
        window.alert( "Hello " + name );
    }
  </script>
</head>
<body>
  <p>Hello <a href="#" onclick="helloWorld('Joe')">Joe</a>!</p>
</body>

In the example above, an alert dialog box with the message "Hello Joe" will appear when the hyperlink is clicked.

The default action can be cancelled by returning false in the event handler:


<head>
  <script type="text/javascript">
    function stayHere()
    {
        // do something
    }
  </script>
</head>
<body>
  <p>Stay <a href="http://www.example.com" onclick="stayHere(); return false;">here</a>!</p>
</body>

In the example above, the browser will not go to "example.com" when the hyperlink is clicked.

While the inline model is not as flexible as other models, it is the only model that allow the registration of event handlers with custom arguments, e.g. name in the helloWorld method.

Traditional model

In the traditional model, event handler can be added/removed with script. Like the inline model, each event can be only one event handler registered. Event handlers are added by assigning a function to the corresponding event property of an object (usually an Element). To remove an event handler, simply set the property to empty:


<head>
  <script type="text/javascript">
    function helloWorld(e)
    {
        window.alert( "Hello World" );
    }

    // Add an event handler
    window.onload = function (e) { window.alert("loaded!"); };

    // Add another event handler
    document.body.onclick = helloWorld;

    // Remove the event handler just added
    document.body.onclick = null;
  </script>
</head>
<body>
  <p>Hello World!</p>
</body>

DOM Level 2

The W3C designed a more flexible event handling model in the DOM Level 2 Events specification.

Name Description Argument type Argument name
addEventListener Allows the registration of event listeners on the event target. DOMString type
EventListener listener
boolean useCapture
removeEventListener Allows the removal of event listeners from the event target. DOMString type
EventListener listener
boolean useCapture
dispatchEvent Allows the dispatch of events into the implementations event model. Event evt

The biggest advantage this model provides over the traditional model is that multiple event handlers can be registered to listen for the same event on a single object. The useCapture option can also prevent bubbling of event. It is supported by Mozilla based browsers, Opera, Safari and Konqueror.

A rewrite of the above example used in traditional model:


<head>
  <script type="text/javascript">
    function helloWorld(e)
    {
        window.alert( "Hello World" );
    }

    // Add an event handler
    window.addEventListener( "load", function (e) {
        window.alert("loaded!");
    }, false );  // No bubbling

    // Add another event handler
    document.body.addEventListener( "click", helloWorld, true );  // Bubbling

    // Remove the event handler just added
    document.body.removeEventListener( "click", helloWorld, true );
  </script>
</head>
<body>
  <p>Hello World!</p>
</body>

Microsoft-specific model

Microsoft Internet Exlporer does not follow the W3C model as a similar model was implemented before the W3C's specification was published.

Name Description Argument type Argument name
attachEvent Similar to W3C's addEventListener method. String type
Function listener
detachEvent Similar to W3C's removeEventListener method. String type
Function listener
fireEvent Similar to W3C's dispatchEvent method. String type
Event evt

While the model is almost idential to W3C's one, there are two important drawbacks:

  1. Events always bubble, no capturing possibility.
  2. The event handling function is referenced, not copied, so the this keyword always refers to the window and is completely useless.

This model is only used in Internet Explorer.

A rewrite of the example used in traditional model:


<head>
  <script type="text/javascript">
    function helloWorld()
    {
        window.alert( "Hello World" );
    }

    // Add an event handler
    window.attachEvent( "onload", function () { alert("loaded!"); } );

    // Add another event handler
    document.body.attachEvent( "onclick", helloWorld );

    // Remove the event handler just added
    document.body.detachEvent( "onclick", helloWorld );
  </script>
</head>
<body>
  <p>Hello World!</p>
</body>

See also

  • XML Events

References

External links

The contents of this article are licensed from Wikipedia.org under the GNU Free Documentation License. How to see transparent copy