DOM events

From Wikipedia, the free encyclopedia

Jump to: navigation, search

DOM (Document Object Model) 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 compatibility problems. To combat this, the event model was standardized by the W3C in DOM Level 2.

Contents

[edit] Events

[edit] HTML events

[edit] Common/W3C events

There is a huge collection of events that can be generated by most element nodes:

  • Mouse events
  • Keyboard events
  • HTML frame/object events
  • HTML form events
  • User 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 is moved onto an element Yes Yes
mousemove onmousemove Fires when the pointing device is moved while it is over an element Yes No
mouseout onmouseout Fires when the pointing device is moved away from an element Yes Yes
Keyboard keypress onkeypress Fires after keydown, when a key on the keyboard is pressed. 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 the user agent finishes loading all content within a document, including window, frames, objects and images

For elements, it fires when the target element and all of its content has finished loading

No No
unload onunload Fires when the user agent removes all content from a window or frame

For elements, it fires when the target element or any of its content has been removed

No No
abort onabort Fires when an object/image is stopped from loading 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 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 tab navigation No No
blur onblur Fires when an element loses focus either via the pointing device or by tabbing navigation 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 Fires 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 has been removed from a DOM-tree Yes No
DOMNodeRemovedFromDocument ondomnoderemovedfromdocument Fires when a node is being removed from a document No No
DOMNodeInsertedIntoDocument ondomnodeinsertedintodocument 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 events whose names start with “DOM” are currently not well supported. Mozilla and Opera support DOMAttrModified, DOMNodeInserted, DOMNodeRemoved and DOMCharacterDataModified. Safari, as of version 1.3, also supports these methods.

[edit] Microsoft-specific events

Two major types of events are added by Microsoft and in some cases can only be used in Internet Explorer others have been implemented as de-facto standards by other browsers:

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

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). Mozilla and Safari also support contextmenu, but Internet Explorer for the Mac does not.

[edit] 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 first moves over an element during a drag. It is similar to the mouseover event but occurs while dragging. No No
dragexit ondragexit Fires when the mouse pointer moves away from an element during a drag. It is also called after a drop on an element. It is similar to the mouseout event but occurs 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

[edit] Other events

For Mozilla and Opera 9, there are also undocumented events known as "DOMContentLoaded" and "DOMFrameContentLoaded" which fire when the DOM content is loaded. These are different from "load" as they fire before the loading of related files (e.g., images). The "DOMContentLoaded" event was also implemented in Safari 3.1.

Opera 9 also supports the Web Forms 2.0 events "DOMControlValueChanged", "invalid", "forminput" and "formchange".

[edit] Event flow

Consider the situation 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 (with method event.stopPropagation() for Mozilla and command event.cancelBubble = true for Internet Explorer), and/or by cancelling the default action for the event.

[edit] Event object

The Event object provides a lot 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 cancelable, 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.

[edit] Event handling models

[edit] DOM Level 0

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

[edit] Inline model

In the inline model, event handlers are added as attribute of element. Event handlers can also be removed:


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

    function removeHandler(object)
    {
        object.onclick = null;
    }
  </script>
</head>
<body>
  <p>Hello <a href="http://www.example.com" onclick="helloWorld('Joe'); removeHandler(this);">Joe</a>!</p>
</body>

In the example above, an alert dialog box with the message "Hello Joe" will appear when the hyperlink is clicked and open URI in href attribute.

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


<head>
  <script type="text/javascript">
    function helloWorld( name )
    {
        window.alert( "Hello " + name );
    }
  </script>
</head>
<body>
  <p>Stay <a href="http://www.example.com" onclick="helloWorld('Joe'); return false;">here</a>!</p>
</body>

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

One common misconception with the inline model is the belief that it allows the registration of event handlers with custom arguments, e.g. name in the helloWorld function. While it may seem like that is the case in the example above, what is really happening is that the JavaScript engine of the browser creates an anonymous function containing the statements in the onclick attribute. The onclick handler of the element would be bound to the following anonymous function:


function()
{
    helloWorld('Joe');
    return false;
}

This limitation of the JavaScript event model is usually overcome by assigning attributes to the function object of the event handler or by using closures.

[edit] Traditional model

In the traditional model, event handlers can be added/removed by scripts. Like the inline model, each event can only have one event handler registered. The event is added by assigning the handler name to the event property of the element object. To remove an event handler, simply set the property to null:


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

    // Add an event handler
    window.onload = helloWorld;

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

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

To add parameters:


var name='Joe';
document.onclick = function(e)
{
 alert('Hello '+ name +'!');
}

Inner functions preserve their scope.

[edit] DOM Level 2

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

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 to send the event to the subscribed event listeners. Event evt


Some useful things to know :

  • To prevent an event to bubble, developers must call the "stopPropagation()" method of the event object.
  • To prevent the default action of the event to be called, developers must call the "preventDefault" method of the event object.

The main difference from the traditional model is that multiple event handlers can be registered for the same event. The useCapture option can also be used to specify that the handler should be called in the capture phase instead of the bubbling phase. This model is supported by Mozilla, Opera, Safari, Chrome and Konqueror.

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.addEventListener( "load", helloWorld, false );  // bubbling phase

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

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

[edit] Microsoft-specific model

Microsoft do not follow the W3C model, as their own model was created prior to the ratification of the W3C standard.

Name Description Argument type Argument name
attachEvent Similar to W3C's addEventListener method. String sEvent
Pointer fpNotify
detachEvent Similar to W3C's removeEventListener method. String sEvent
Pointer fpNotify
fireEvent Similar to W3C's dispatchEvent method. String sEvent
Event oEventObject

Some useful things to know :

  • To prevent an event bubbling, developers must set the event's "cancelBubble" property.
  • To prevent the default action of the event to be called, developers must set the event's "returnValue" property.
  • The this keyword refers to the global window object.

Again, this model differs from the traditional model in that multiple event handlers can be registered for the same event. However the useCapture option can not be used to specify that the handler should be called in the capture phase. This model is supported by Microsoft Internet Explorer and Trident based browsers (e.g. Maxthon, Avant Browser).

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", helloWorld );

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

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

[edit] See also

[edit] References

[edit] External links

Personal tools
Languages