DOM events


DOM events are actions that occurs as a result of the user action or as result of state change of the elements of a DOM tree. Client-side scripting languages like JavaScript, JScript, ECMAScript, VBScript, and Java can register various event handlers or listeners on the element nodes inside a DOM tree, such as in HTML, XHTML, XUL, and SVG documents.
Examples of HTML DOM events:
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 World Wide Web Consortium in DOM Level 2.

Events

HTML events

Common events

There is a huge collection of events that can be generated by most element nodes:
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
MousedblclickondblclickFires when the pointing device button is double-clicked over an elementYesYes
MousemousedownonmousedownFires when the pointing device button is pressed over an elementYesYes
MousemouseuponmouseupFires when the pointing device button is released over an elementYesYes
MousemouseoveronmouseoverFires when the pointing device is moved onto an elementYesYes
MousemousemoveonmousemoveFires when the pointing device is moved while it is over an elementYesYes
MousemouseoutonmouseoutFires when the pointing device is moved away from an elementYesYes
MousedragstartondragstartFired on an element when a drag is started.YesYes
MousedragondragThis event is fired at the source of the drag, that is, the element where dragstart was fired, during the drag operation.YesYes
MousedragenterondragenterFired when the mouse is first moved over an element while a drag is occurring.YesYes
MousedragleaveondragleaveThis event is fired when the mouse leaves an element while a drag is occurring.YesNo
MousedragoverondragoverThis event is fired as the mouse is moved over an element when a drag is occurring.YesYes
MousedropondropThe drop event is fired on the element where the drop occurs at the end of the drag operation.YesYes
MousedragendondragendThe source of the drag will receive a dragend event when the drag operation is complete, whether it was successful or not.YesNo
KeyboardkeydownonkeydownFires before keypress, when a key on the keyboard is pressed.YesYes
KeyboardkeypressonkeypressFires after keydown, when a key on the keyboard is pressed.YesYes
KeyboardkeyuponkeyupFires when a key on the keyboard is releasedYesYes
HTML frame/objectloadonloadFires when the user agent finishes loading all content within a document, including window, frames, objects and imagesFor elements, it fires when the target element and all of its content has finished loadingNoNo
HTML frame/objectunloadonunloadFires 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
NoNo
HTML frame/objectabortonabortFires when an object/image is stopped from loading before completely loadedYesNo
HTML frame/objecterroronerrorFires when an object/image/frame cannot be loaded properlyYesNo
HTML frame/objectresizeonresizeFires when a document view is resizedYesNo
HTML frame/objectscrollonscrollFires when an element or document view is scrolledNo, except that a scroll event on document must bubble to the windowNo
HTML formselectonselectFires when a user selects some text in a text field, including input and textareaYesNo
HTML formchangeonchangeFires when a control loses the input focus and its value has been modified since gaining focusYesNo
HTML formsubmitonsubmitFires when a form is submittedYesYes
HTML formresetonresetFires when a form is resetYesNo
HTML formfocusonfocusFires when an element receives focus either via the pointing device or by tab navigationNoNo
HTML formbluronblurFires when an element loses focus either via the pointing device or by tabbing navigationNoNo
User interfacefocusinSimilar to HTML focus event, but can be applied to any focusable elementYesNo
User interfacefocusoutSimilar to HTML blur event, but can be applied to any focusable elementYesNo
User interfaceDOMActivateSimilar to XUL command event. Fires when an element is activated, for instance, through a mouse click or a keypress.YesYes
MutationDOMSubtreeModifiedFires when the subtree is modifiedYesNo
MutationDOMNodeInsertedFires when a node has been added as a child of another nodeYesNo
MutationDOMNodeRemovedFires when a node has been removed from a DOM-treeYesNo
MutationDOMNodeRemovedFromDocumentFires when a node is being removed from a documentNoNo
MutationDOMNodeInsertedIntoDocumentFires when a node is being inserted into a documentNoNo
MutationDOMAttrModifiedFires when an attribute has been modifiedYesNo
MutationDOMCharacterDataModifiedFires when the character data has been modifiedYesNo
ProgressloadstartProgress has begun.NoNo
ProgressprogressIn progress. After loadstart has been dispatched.NoNo
ProgresserrorProgression failed. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.NoNo
ProgressabortProgression is terminated. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.NoNo
ProgressloadProgression is successful. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.NoNo
ProgressloadendProgress has stopped. After one of error, abort, or load has been dispatched.NoNo

Note that the events whose names start with "DOM" are currently not well supported, and for this and other performance reasons are deprecated by the W3C in DOM Level 3. Mozilla and Opera support DOMAttrModified, DOMNodeInserted, DOMNodeRemoved and DOMCharacterDataModified. Chrome and Safari support these events, except for DOMAttrModified.

Touch events

Web browsers running on touch-enabled devices, such as Apple's iOS and Google's Android, generate additional events.
CategoryTypeAttributeDescriptionBubblesCancelable
TouchtouchstartFires when a finger is placed on the touch surface/screen.YesYes
TouchtouchendFires when a finger is removed from the touch surface/screen.YesYes
TouchtouchmoveFires when a finger already placed on the screen is moved across the screen.YesYes
TouchtouchenterFires when a touch point moves onto the interactive area defined by a DOM element.YesYes
TouchtouchleaveFires when a touch point moves off the interactive area defined by a DOM element.YesYes
TouchtouchcancelA user agent must dispatch this event type to indicate when a TouchPoint has been disrupted in an implementation-specific manner, such as by moving outside the bounds of the UA window. A user agent may also dispatch this event type when the user places more touch points on the touch surface than the device or implementation is configured to store, in which case the earliest TouchPoint object in the TouchList should be removed.YesNo

In the W3C draft recommendation, a TouchEvent delivers a TouchList of Touch locations, the modifier keys that were active, a TouchList of Touch locations within the targeted DOM element, and a TouchList of Touch locations that have changed since the previous TouchEvent.
Apple didn't join this working group, and delayed W3C recommendation of its Touch Events Specification by disclosing patents late in the recommendation process.

Pointer events

Web browsers on devices with various types of input devices including mouse, touch panel, and pen may generate integrated input events. Users can see what type of input device is pressed, what button is pressed on that device, and how strongly the button is pressed when it comes to a stylus pen. As of October 2013, this event is only supported by Internet Explorer 10 and 11.
CategoryTypeAttributeDescriptionBubblesCancelable
PointerpointerdownonpointerdownFires when the pointing device button is activated, or pressed over an element.YesYes
PointerpointeruponpointerupFires when the pointing device button is released over an elementYesYes
PointerpointercancelonpointercancelFires when a pointing device is unlikely to continue to produce event because, for example, the device is used for panning/zooming after a pointerdown event.YesYes
PointerpointermoveonpointermoveFires when the pointing device is moved while it is over an elementYesYes
PointerpointeroveronpointeroverFires when the pointing device is moved onto an elementYesYes
PointerpointeroutonpointeroutFires when the pointing device is moved away from an element. Also fires after pointerup by pointing device without hovering, or afterYesYes
PointerpointerenteronpointerenterFires when the pointing device is moved onto an element, or when the button of the pointing device which does not support hovering is pressed on one of its descendant elements.NoYes
PointerpointerleaveonpointerleaveFires when the pointing device is moved away from an element, or when the button of the pointing device which does not support hovering is released over its descendant elements.NoYes
PointergotpointercaptureongotpointercaptureFires when the pointer is captured by setPointerCapture method.YesNo
PointerlostpointercaptureonlostpointercaptureFires when the pointer is released by releasePointerCapture method.YesNo

Indie UI events

Not yet really implemented, the Indie UI working groups want to help web application developers to be able to support standard user interaction events without having to handle different platform specific technical events that could match with it.
Scripting usable interfaces can be difficult, especially when one considers that user interface design patterns differ across software platforms, hardware, and locales, and that those interactions can be further customized based on personal preference. Individuals are accustomed to the way the interface works on their own system, and their preferred interface frequently differs from that of the web application author's preferred interface.
For example, web application authors, wishing to intercept a user's intent to undo the last action, need to "listen" for all the following events:
It would be simpler to listen for a single, normalized request to "undo" the previous action.
CategoryTypeDescriptionBubblesCancelable
RequestundorequestIndicates the user desires to "undo" the previous action. YesYes
RequestredorequestIndicates the user desires to "redo" the previously "undone" action. Yesno
RequestexpandrequestIndicates the user desires to reveal information in a collapsed section or branch node in a hierarchy.YesYes
RequestcollapserequestIndicates the user desires to hide or collapse information in an expanded section or branch node in a hierarchy.YesYes
RequestdismissrequestIndicates the user desires "dismiss" the current view.YesYes
RequestdeleterequestIndicates the user wants to initiate a "delete" action on the marked element or current view.YesYes
Focus RequestdirectionalfocusrequestInitiated when the user agent sends a "direction focus" request to the web application. Web authors should not use or register for directionalfocusrequest events when standard browser focus and blur events are sufficient. Using these events unnecessarily could result in reduced performance or negative user experience.YesYes
Focus RequestlinearfocusrequestInitiated when the user agent sends a "linear focus" request to the web application. Web authors should not use or register for linearfocusrequest events when standard browser focus and blur events are sufficient. This event type is only necessary on specialized control types such as data grids where the logical next element may not be focusable or even in the DOM until requested. Using these events unnecessarily could result in reduced performance or negative user experience.YesYes
Focus RequestpalettefocusrequestInitiated when the user agent sends a "palette focus" request to the web application. Web app authors receiving this event should move focus to the first palette in the web application, or cycle focus between all available palettes. Note: palettes are sometimes referred to as non-modal dialogs or inspector windows.YesYes
Focus RequesttoolbarfocusrequestInitiated when the user agent sends a "toolbar focus" request to the web application. Web app authors receiving this event should move focus to the main toolbar in the web application, or cycle focus between all available toolbars.YesYes
Manipulation RequestmoverequestInitiated when the user agent sends a move request to the web application with accompanying x/y delta values. This is used, for example, when moving an object to a new location on a layout canvas.YesYes
Manipulation RequestpanrequestInitiated when the user agent sends a pan request to the web application with accompanying x/y delta values. This is used, for example, when changing the center point while panning a map or another custom image viewer.YesYes
Manipulation RequestrotationrequestInitiated when the user agent sends a rotation request to the web application with accompanying origin x/y values and a rotation value in degrees.YesYes
Manipulation RequestzoomrequestInitiated when the user agent sends a zoom request to the web application with accompanying origin x/y values and the zoom scale factor.YesYes
Scroll RequestscrollrequestInitiated when the user agent sends a scroll request to the web application with accompanying x/y delta values or one of the other defined scrollType values. Authors should only use this event and uiaction with custom scroll views.YesYes
ValueChange RequestvaluechangerequestInitiated when the user agent sends a value change request to the web application. Used on custom range controls like sliders, carousels, etc.YesYes

Internet Explorer-specific events

In addition to the common events, two major types of events are added by Internet Explorer. Some of the events have been implemented as de facto standards by other browsers.
CategoryTypeAttributeDescriptionBubblesCancelable
ClipboardcutoncutFires after a selection is cut to the clipboard.YesYes
ClipboardcopyoncopyFires after a selection is copied to the clipboard.YesYes
ClipboardpasteonpasteFires after a selection is pasted from the clipboard.YesYes
ClipboardbeforecutonbeforecutFires before a selection is cut to the clipboard.YesYes
ClipboardbeforecopyonbeforecopyFires before a selection is copied to the clipboard.YesYes
ClipboardbeforepasteonbeforepasteFires before a selection is pasted from the clipboard.YesYes
Data bindingafterupdateonafterupdateFires immediately after a databound object has been updated.YesNo
Data bindingbeforeupdateonbeforeupdateFires before a data source is updated.YesYes
Data bindingcellchangeoncellchangeFires when a data source has changed.YesNo
Data bindingdataavailableondataavailableFires when new data from a data source become available.YesNo
Data bindingdatasetchangedondatasetchangedFires when content at a data source has changed.YesNo
Data bindingdatasetcompleteondatasetcompleteFires when transfer of data from the data source has completed.YesNo
Data bindingerrorupdateonerrorupdateFires if an error occurs while updating a data field.YesNo
Data bindingrowenteronrowenterFires when a new row of data from the data source is available.YesNo
Data bindingrowexitonrowexitFires when a row of data from the data source has just finished.NoYes
Data bindingrowsdeleteonrowsdeleteFires when a row of data from the data source is deleted.YesNo
Data bindingrowinsertedonrowinsertedFires when a row of data from the data source is inserted.YesNo
MousecontextmenuoncontextmenuFires when the context menu is shown.YesYes
MousedragondragFires when during a mouse drag.YesYes
MousedragstartondragstartFires when a mouse drag begins.YesYes
MousedragenterondragenterFires when something is dragged onto an area.YesYes
MousedragoverondragoverFires when a drag is held over an area.YesYes
MousedragleaveondragleaveFires when something is dragged out of an area.YesYes
MousedragendondragendFires when a mouse drag ends.YesYes
MousedropondropFires when a mouse button is released over a valid target during a drag.YesYes
MouseselectstartonselectstartFires when the user starts to select text.YesYes
KeyboardhelponhelpFires when the user initiates help.YesYes
HTML frame/objectbeforeunloadonbeforeunloadFires before a document is unloaded.NoYes
HTML frame/objectstoponstopFires when the user stops loading the object. NoNo
HTML formbeforeeditfocusonbeforeeditfocusFires before an element gains focus for editing.YesYes
MarqueestartonstartFires when a marquee begins a new loop.NoNo
MarqueefinishonfinishFires when marquee looping is complete.NoYes
MarqueebounceonbounceFires when a scrolling marquee bounces back in the other direction.NoYes
MiscellaneousbeforeprintonbeforeprintFires before a document is printedNoNo
MiscellaneousafterprintonafterprintFires immediately after the document prints.NoNo
MiscellaneouspropertychangeonpropertychangeFires when the property of an object is changed.NoNo
MiscellaneousfilterchangeonfilterchangeFires when a filter changes properties or finishes a transition.NoNo
MiscellaneousreadystatechangeonreadystatechangeFires when the readyState property of an element changes.NoNo
MiscellaneouslosecaptureonlosecaptureFires when the releaseCapture method is invoked.NoNo

Note that Mozilla, Safari and Opera also support the readystatechange event for the XMLHttpRequest object. Mozilla also supports the beforeunload event using the traditional event registration method. Mozilla and Safari also support contextmenu, but Internet Explorer for Mac does not.
Note that Firefox 6 and later support the beforeprint and afterprint events.

XUL events

In addition to the common 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.YesYes
MousedragdropondragdropFires when the user releases the mouse button to drop an object being dragged.NoNo
MousedragenterondragenterFires when the mouse pointer first moves over an element during a drag. It is similar to the mouseover event but occurs while dragging.NoNo
MousedragexitondragexitFires 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
MousedraggestureondraggestureFires when the user starts dragging the element, usually by holding down the mouse button and moving the mouse.NoNo
MousedragoverondragoverRelated 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
InputRadioStateChangeFires when a radio button is selected, either by the user or a script.NoNo
InputcloseoncloseFires when a request has been made to close the window.NoYes
InputcommandoncommandSimilar to W3C DOMActivate event. Fires when an element is activated, for instance, through a mouse click or a keypress.NoNo
InputinputoninputFires when a user enters text in a textbox.YesNo
User interfaceDOMMenuItemActiveDOMMenuItemActiveFires when a menu or menuitem is hovered over, or highlighted.YesNo
User interfaceDOMMenuItemInactiveDOMMenuItemInactiveFires when a menu or menuitem is no longer being hovered over, or highlighted.YesNo
User interfacecontextmenuoncontextmenuFires 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
User interfaceoverflowonoverflowFires a box or other layout element when there is not enough space to display it at full size.NoNo
User interfaceoverflowchangedonoverflowchangedFires when the overflow state changes.NoNo
User interfaceunderflowonunderflowFires to an element when there becomes enough space to display it at full size.NoNo
User interfacepopuphiddenonpopuphiddenFires to a popup after it has been hidden.NoNo
User interfacepopuphidingonpopuphidingFires to a popup when it is about to be hidden.NoNo
User interfacepopupshowingonpopupshowingFires to a popup just before it is popped open.NoYes
User interfacepopupshownonpopupshownFires 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
CommandcommandupdateoncommandupdateFires when a command update occurs.NoNo

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. However, DOMContentLoaded has been added to the HTML 5 specification.
The DOMContentLoaded event was also implemented in the Webkit rendering engine build 500+. This correlates to all versions of Google Chrome and Safari 3.1+. DOMContentLoaded is also implemented in Internet Explorer 9.
Opera 9 also supports the Web Forms 2.0 events DOMControlValueChanged, invalid, forminput and formchange.

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:
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 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 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.
NameTypeDescription
typeDOMStringThe name of the event.
targetEventTargetUsed to indicate the EventTarget to which the event was originally dispatched.
currentTargetEventTargetUsed to indicate the EventTarget whose EventListeners are currently being processed.
eventPhaseunsigned shortUsed to indicate which phase of event flow is currently being evaluated.
bubblesbooleanUsed to indicate whether or not an event is a bubbling event.
cancelablebooleanUsed to indicate whether or not an event can have its default action prevented.
timeStampDOMTimeStampUsed to specify the time at which the event was created.

NameArgument typeArgument nameDescription
stopPropagationTo prevent further propagation of an event during event flow.
preventDefaultTo 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.
initEventDOMStringeventTypeArgSpecifies the event type.
initEventbooleancanBubbleArgSpecifies whether or not the event can bubble.
initEventbooleancancelableArgSpecifies 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. There are two model types: the inline model and the traditional model.

Inline model

In the inline model, event handlers are added as attributes of elements. In the example below, an alert dialog box with the message "Hey Joe" appears after the hyperlink is clicked. The default click action is cancelled by returning false in the event handler.





Inline Event Handling


Inline Event Handling


Hey Joe!






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

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





Traditional Event Handling


Traditional Event Handling


Hey Joe!






To add parameters:

var name = 'Joe';
document.onclick = );

Inner functions preserve their scope.

DOM Level 2

The W3C designed a more flexible event handling model in DOM Level 2.
NameDescriptionArgument typeArgument name
addEventListenerAllows the registration of event listeners on the event target.DOMStringtype
addEventListenerAllows the registration of event listeners on the event target.EventListenerlistener
addEventListenerAllows the registration of event listeners on the event target.booleanuseCapture
removeEventListenerAllows the removal of event listeners from the event target.DOMStringtype
removeEventListenerAllows the removal of event listeners from the event target.EventListenerlistener
removeEventListenerAllows the removal of event listeners from the event target.booleanuseCapture
dispatchEventAllows sending the event to the subscribed event listeners.Eventevt

Some useful things to know :
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 the traditional model






DOM Level 2


DOM Level 2



Hey Joe!







Internet Explorer-specific model

Microsoft Internet Explorer prior to version 8 does not follow the W3C model, as its own model was created prior to the ratification of the W3C standard. Internet Explorer 9 follows DOM level 3 events, and Internet Explorer 11 deletes its support for Microsoft-specific model.
NameDescriptionArgument typeArgument name
attachEventSimilar to W3C's addEventListener method.StringsEvent
attachEventSimilar to W3C's addEventListener method.PointerfpNotify
detachEventSimilar to W3C's removeEventListener method.StringsEvent
detachEventSimilar to W3C's removeEventListener method.PointerfpNotify
fireEventSimilar to W3C's dispatchEvent method.StringsEvent
fireEventSimilar to W3C's dispatchEvent method.EventoEventObject

Some useful things to know :
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.

A rewrite of the example used in the old Internet Explorer-specific model






Internet Explorer-specific model


Internet Explorer-specific model


Hey Joe!