AllExperts > Encyclopedia 
Search      
Find out about volunteering to AllExperts

DOM Events: Encyclopedia BETA


Free Encyclopedia
 Home · Index · Browse A-Z  · Questions and Answers ·
Encyclopedia

Browse A-Z
ABCDEFGHIJKLMNOPQRSTUVWXYZNum


License
Disclaimer

 
 
 
 
Free Online Courses
12 Weeks to Weight Loss
Take Charge of Stress
Learn How to Bake
Budgeting 101
Deeper Faith
DIY Fashion Makeover

       MORE E-COURSES
 
   

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z  Misc

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. DOM is an acronym for the Document Object Model.

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.

Events

HTML events

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.
CategoryTypeAttributeDescriptionBubblesCancelable
MouseclickonclickFires 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
YesYes
dblclickondblclickFires when the pointing device button is double clicked over an element.YesYes
mousedownonmousedownFires when the pointing device button is pressed over an element.YesYes
mouseuponmouseupFires when the pointing device button is released over an element.YesYes
mouseoveronmouseoverFires when the pointing device button is moved onto an element.YesYes
mousemoveonmousemoveFires when the pointing device button is moved while it is over an element.YesNo
mouseoutonmouseoutFires when the pointing device button is moved away from an element.YesYes
KeyboardkeypressonkeypressFires when a key on the keyboard is "clicked". A keypress is defined as a keydown and keyup on the same key. The sequence of these events is:
*keydown
*keyup
*keypress
YesYes
keydownonkeydownFires when a key on the keyboard is pressed.YesYes
keyuponkeyupFires when a key on the keyboard is released.YesYes
HTML frame/objectloadonloadFires when finishes loading all content within a document, including window, frame, object and image.NoNo
unloadonunloadFires when removes all content from a window or frame.NoNo
abortonabortFires when an object/image loading is stopped before completely loaded.YesNo
erroronerrorFires when an object/image/frame cannot be loaded properly.YesNo
resizeonresizeFires when a document view is resized.YesNo
scrollonscrollFires when a document view is scrolled.YesNo
HTML formselectonselectFires when a user selects some text in a text field, including input and textarea.YesNo
changeonchangeFires when a control loses the input focus and its value has been modified since gaining focus, including input, select and textarea.YesNo
submitonsubmitFires when a form is submitted.YesYes
resetonresetFires when a form is reset.YesNo
focusonfocusFires when an element receives focus either via the pointing device or by tabbing navigation, including label, input, select, textarea, and button.NoNo
bluronblurFires when an element loses focus either via the pointing device or by tabbing navigation, including label, input, select, textarea, and button.NoNo
User interfaceDOMFocusInondomfocusinSimilar to HTML focus event, but can be applied to any focusable element.YesNo
DOMFocusOutondomfocusoutSimilar to HTML blur event, but can be applied to any focusable element.YesNo
DOMActivateondomactivateSimilar to XUL command event. Fires when an element is activated, for instance, through a mouse click or a keypress.YesYes
MutationDOMSubtreeModifiedonsubtreemodifiedFire when the subtree is modified.YesNo
DOMNodeInsertedonnodeinsertedFires when a node has been added as a child of another node.YesNo
NodeInsertedIntoDocumentonnodeinsertedintodocumentFires when a node is being inserted into a document.NoNo
DOMAttrModifiedonattrmodifiedFires when an attribute has been modified.YesNo
DOMCharacterDataModifiedoncharacterdatamodifiedFires when the character data has been modified.YesNo
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.

Microsoft-specific events

Two major types of events are added by Microsoft and can only be used in Internet Explorer:
*Clipboard events
*Data binding events
CategoryTypeAttributeDescriptionBubblesCancelable
ClipboardcutoncutFires after a selection is cut to the clipboard.?Yes
copyoncopyFires after a selection is copied to the clipboard.?Yes
pasteonpasteFires after a selection is pasted from the clipboard.?Yes
beforecutonbeforecutFires before a selection is cut to the clipboard.??
beforecopyonbeforecopyFires before a selection is copied to the clipboard.??
beforepasteonbeforepasteFires before a selection is pasted from the clipboard.??
Data bindingafterupdateonafterupdateFires immediately after a databound object has been updated.??
beforeupdateonbeforeupdateFires before a data source is updated.??
cellchangeoncellchangeFires when a data source has changed.??
dataavailableondataavailableFires when new data from a data source become available.??
datasetchangeondatasetchangeFires when content at a data source has changed.??
datasetcompleteondatasetcompleteFires when transfer of data from the data source has completed.??
errorupdateonerrorupdateFires if an error occurs while updating a data field.??
rowenteronrowenterFires when a new row of data from the data source is available.??
rowexitonrowexitFires when a row of data from the data source has just finished.??
rowdeleteonrowdeleteFires when a row of data from the data source is deleted.??
rowinsertedonrowinsertedFires when a row of data from the data source is inserted.??
MousecontextmenuoncontextmenuFires when the context menu is shown.??
dragondragFires when during a mouse drag.??
dragstartondragstartFires when a mouse drag begins.?yes
dragenterondragenterFires when something is dragged onto an area.??
dragoverondragoverFires when a drag is held over an area.??
dragleaveondragleaveFires when something is dragged out of an area.??
dragendondragendFires when a mouse drag ends.??
dropondropFires when a mouse button is released over a valid target during a drag.??
KeyboardhelponhelpFires when the user initiates help.??
HTML frame/objectbeforeunloadonbeforeunloadFires before a document is unloaded.??
stoponstopFires when the user stops loading the object. (Same as abort event?)??
HTML formselectstartonselectstartFires when the object is selected.??
beforeeditfocusonbeforeeditfocusFires before an element gains focus for editing.??
MarqueestartonstartFires when a marquee begins a new loop.??
endonendFires when a marquee finishes its scrolling.??
bounceonbounceFires when a scrolling marquee bounces back in the other direction.??
MiscellaneousbeforeprintonbeforeprintFires before a document is printed??
afterprintonafterprintFires immediately after the document prints.??
propertychangeonpropertychangeFires when the property of an object is changed.??
filterchangeonfilterchangeFires when a filter changes properties or finishes a transition.??
readystatechangeonreadystatechangeFires when the readyState property of an element changes.??
lostcaptureonlostcaptureFires 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). Mozilla and Safari also support contextmenu, but Internet Explorer for the Mac does not.

XUL events

In addition to the common/W3C events, Mozilla defined a set of events that work only with XUL elements.
CategoryTypeAttributeDescriptionBubblesCancelable
MouseDOMMouseScrollDOMMouseScrollFires when the mouse wheel is moved, causing the content to scroll.NoNo
dragdropondragdropFires when the user releases the mouse button to drop an object being dragged.NoNo
dragenterondragenterFires when the mouse pointer first moves over an element during a drag. It is similar to the mouseover event but occurs while dragging.NoNo
dragexitondragexitFires 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.NoNo
draggestureondraggestureFires when the user starts dragging the element, usually by holding down the mouse button and moving the mouse.NoNo
dragoverondragoverRelated to the mousemove event, this event is fired while something is being dragged over an element.NoNo
InputCheckboxStateChangeFires when a checkbox is checked or unchecked, either by the user or a script.NoNo
RadioStateChangeFires when a radio button is selected, either by the user or a script.NoNo
closeoncloseFires when a request has been made to close the window.NoYes
commandoncommandSimilar to W3C DOMActivate event. Fires when an element is activated, for instance, through a mouse click or a keypress.NoNo
inputoninputFires when a user enters text in a textbox.NoNo
User interfaceDOMMenuItemActiveDOMMenuItemActiveFires when a menu or menuitem is hovered over, or highlighted.YesNo
DOMMenuItemInactiveDOMMenuItemInactiveFires when a menu or menuitem is no longer being hovered over, or highlighted.YesNo
contextmenuoncontextmenuFires 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.NoYes
overflowonoverflowFires a box or other layout element when there is not enough space to display it at full size.NoNo
overflowchangedonoverflowchangedFires when the overflow state changes.NoNo
underflowonunderflowFires to an element when there becomes enough space to display it at full size.NoNo
popuphiddenonpopuphiddenFires to a popup after it has been hidden.NoNo
popuphidingonpopuphidingFires to a popup when it is about to be hidden.NoNo
popupshowingonpopupshowingFires to a popup just before it is popped open.NoYes
popupshownonpopupshownFires to a popup after it has been opened, much like the onload event is sent to a window when it is opened.NoNo
CommandbroadcastonbroadcastPlaced on an observer. The broadcast event is sent when the attributes of the broadcaster being listened to are changed.NoNo
commandupdateoncommandupdateFires when a command update occurs.NoNo

Other events

For Mozilla (and Opera 9), 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

Event flow in DOM Level 2

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.

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
TypeName! Description
DOMStringtypeThe name of the event (case-insensitive).
EventTargettargetUsed to indicate the EventTarget to which the event was originally dispatched.
EventTargetcurrentTargetUsed to indicate the EventTarget whose EventListeners are currently being processed.
unsigned shorteventPhaseUsed to indicate which phase of event flow is currently being evaluated.
booleanbubblesUsed to indicate whether or not an event is a bubbling event.
booleancancelableUsed to indicate whether or not an event can have its default action prevented.
DOMTimeStamptimeStampUsed to specify the time (in milliseconds relative to the epoch) at which the event was created.
Event methods
NameArgument typeArgument nameDescription
stopPropagationTo prevent further propagation of an event during event flow.
preventDefaultTo 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.
initEventDOMStringeventTypeArgSpecifies the event type.
booleancanBubbleArgSpecifies whether or not the event can bubble.
booleancancelableArgSpecifies 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 two model types: inline model and traditional model.

Inline model

In the inline model, event handlers are added as attribute of element. Only one event handler per event of the element is allowed. There is no way to remove the event handler from an element:
    

Hello Joe!

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:
    

Stay here!

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.

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:
    

Hello World!

To add parameters:
var name='Joe';document.onclick = function(e){
 alert('Hello '+ name +'!');
}
Inner functions preserve their scope.

DOM Level 2

The W3C designed a more flexible event handling model in DOM Level 2.
NameDescriptionArgument typeArgument name
addEventListener Allows the registration of event listeners on the event target.DOMStringtype
EventListenerlistener
booleanuseCapture
removeEventListener Allows the removal of event listeners from the event target.DOMStringtype
EventListenerlistener
booleanuseCapture
dispatchEventAllows the registration of event listeners on the event target.Eventevt
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 and Konqueror.

A rewrite of the example used in traditional model:
    

Hello World!

Microsoft-specific model

Microsoft does not follow the W3C model, as their model was created prior to the ratification of the W3C standard.
NameDescriptionArgument typeArgument name
attachEvent Similar to W3C's addEventListener method.StringsEvent
PointerfpNotify
detachEvent Similar to W3C's removeEventListener method.StringsEvent
PointerfpNotify
While the model is almost idential to W3C's one, there are two important drawbacks:#Events always bubble, no capturing possibility.#The event handling function is referenced, not copied, so the this keyword refers to the window, rather than the element that triggered the event.This model is only used in Internet Explorer.

A rewrite of the example used in traditional model:
    

Hello World!

See also

*XML Events A syntactic binding to DOM Events

References

*Deitel, Harvey. (2002). Internet and World Wide Web: how to program (Second Edition). ISBN 0130308978
*XULPlanet. (2004). Event Handlers. Retrieved February 16, 2005.
*The Mozilla Organization. (2002). DOM Event Reference. Retrieved February 20, 2005.

External links

*Document Object Model (DOM) Level 2 Events Specification
*Document Object Model (DOM) Level 3 Events Working Draft



Email this page
About Us | Advertise on This Site | User Agreement | Privacy Policy | Kids' Privacy Policy | Help
About and About.com are registered trademarks of About, Inc. The About logo is a trademark of About, Inc. All rights reserved.
This is the "GNU Free Documentation License" reference article from the English Wikipedia. All text is available under the terms of the GNU Free Documentation License. See also our Disclaimer.