Hubbry Logo
DOM eventDOM eventMain
Open search
DOM event
Community hub
DOM event
logo
7 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Contribute something
DOM event
DOM event
from Wikipedia

DOM (Document Object Model) Events are a signal that something has occurred, or is occurring, and can be triggered by user interactions or by the browser.[1] Client-side scripting languages like JavaScript, JScript, 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 DOM Events:

  • When a user clicks the mouse
  • When a web page has loaded
  • When an image has been loaded
  • When the mouse moves over an element
  • When an input field is changed
  • When an HTML form is submitted
  • When a user presses a key[2]

Historically, like DOM, the event models used by various web browsers had some significant differences which caused compatibility problems. To combat this, the event model was standardized by the World Wide Web Consortium (W3C) in DOM Level 2.

Events

[edit]

HTML events

[edit]

Common events

[edit]

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

  • Mouse events.[3][4]
  • Keyboard events.
  • HTML frame/object events.
  • HTML form events.
  • User interface events.
  • Mutation events (notification of any changes to the structure of a document).
  • Progress events[5] (used by XMLHttpRequest and File API[6]).

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[7] onmousemove Fires when the pointing device is moved while it is over an element Yes Yes
mouseout onmouseout Fires when the pointing device is moved away from an element Yes Yes
dragstart ondragstart Fired on an element when a drag is started. Yes Yes
drag ondrag This event is fired at the source of the drag, that is, the element where dragstart was fired, during the drag operation. Yes Yes
dragenter ondragenter Fired when the mouse is first moved over an element while a drag is occurring. Yes Yes
dragleave ondragleave This event is fired when the mouse leaves an element while a drag is occurring. Yes No
dragover ondragover This event is fired as the mouse is moved over an element when a drag is occurring. Yes Yes
drop ondrop The drop event is fired on the element where the drop occurs at the end of the drag operation. Yes Yes
dragend ondragend The source of the drag will receive a dragend event when the drag operation is complete, whether it was successful or not. Yes No
Keyboard keydown onkeydown Fires before keypress, when a key on the keyboard is pressed. Yes Yes
keypress onkeypress Fires after keydown, 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 an element or document view is scrolled No, except that a scroll event on document must bubble to the window[8] 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 focusin (none) Similar to HTML focus event, but can be applied to any focusable element Yes No
focusout (none) Similar to HTML blur event, but can be applied to any focusable element Yes No
DOMActivate (none) Similar to XUL command event. Fires when an element is activated, for instance, through a mouse click or a keypress. Yes Yes
Mutation DOMSubtreeModified (none) Fires when the subtree is modified Yes No
DOMNodeInserted (none) Fires when a node has been added as a child of another node Yes No
DOMNodeRemoved (none) Fires when a node has been removed from a DOM-tree Yes No
DOMNodeRemovedFromDocument (none) Fires when a node is being removed from a document No No
DOMNodeInsertedIntoDocument (none) Fires when a node is being inserted into a document No No
DOMAttrModified (none) Fires when an attribute has been modified Yes No
DOMCharacterDataModified (none) Fires when the character data has been modified Yes No
Progress loadstart (none) Progress has begun. No No
progress (none) In progress. After loadstart has been dispatched. No No
error (none) Progression failed. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched. No No
abort (none) Progression is terminated. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched. No No
load (none) Progression is successful. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched. No No
loadend (none) Progress has stopped. After one of error, abort, or load has been dispatched. No No

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

[edit]

Web browsers running on touch-enabled devices, such as Apple's iOS and Google's Android, generate additional events.[9]: §5.3 

Category Type Attribute Description Bubbles Cancelable
Touch touchstart Fires when a finger is placed on the touch surface/screen. Yes Yes
touchend Fires when a finger is removed from the touch surface/screen. Yes Yes
touchmove Fires when a finger already placed on the screen is moved across the screen. Yes Yes
touchenter Fires when a touch point moves onto the interactive area defined by a DOM element. Yes Yes
touchleave Fires when a touch point moves off the interactive area defined by a DOM element. Yes Yes
touchcancel A 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 (The coordinate point at which a pointer (e.g. finger or stylus) intersects the target surface of an interface) 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.[9]: §5.9  Yes No

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.[9]

Apple didn't join this working group, and delayed W3C recommendation of its Touch Events Specification by disclosing patents late in the recommendation process.[10]

Pointer events

[edit]

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.[11]

Category Type Attribute Description Bubbles Cancelable
Pointer pointerdown onpointerdown Fires when the pointing device button is activated, or pressed over an element. Yes Yes
pointerup onpointerup Fires when the pointing device button is released over an element Yes Yes
pointercancel onpointercancel Fires 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. Yes Yes
pointermove onpointermove Fires when the pointing device is moved while it is over an element Yes Yes
pointerover onpointerover Fires when the pointing device is moved onto an element Yes Yes
pointerout onpointerout Fires when the pointing device is moved away from an element. Also fires after pointerup by pointing device without hovering, or after Yes Yes
pointerenter onpointerenter Fires 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. No Yes
pointerleave onpointerleave Fires 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. No Yes
gotpointercapture ongotpointercapture Fires when the pointer is captured by setPointerCapture method. Yes No
lostpointercapture onlostpointercapture Fires when the pointer is released by releasePointerCapture method. Yes No

Indie UI events

[edit]

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.[12]

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:

  • Control+Z on Windows and Linux.
  • Command+Z on Mac OS X.
  • Shake events on some mobile devices.

It would be simpler to listen for a single, normalized request to "undo" the previous action.

Category Type Description Bubbles Cancelable
Request undorequest Indicates the user desires to "undo" the previous action. (May be superseded by the UndoManager interface.) Yes Yes
redorequest Indicates the user desires to "redo" the previously "undone" action. (May be superseded by the UndoManager interface.) Yes No
expandrequest Indicates the user desires to reveal information in a collapsed section (e.g. a disclosure widget) or branch node in a hierarchy (e.g., a tree view). Yes Yes
collapserequest Indicates the user desires to hide or collapse information in an expanded section (e.g. a disclosure widget) or branch node in a hierarchy (e.g., a tree view). Yes Yes
dismissrequest Indicates the user desires "dismiss" the current view (e.g. canceling a dialog, or closing a popup menu). Yes Yes
deleterequest Indicates the user wants to initiate a "delete" action on the marked element or current view. Yes Yes
Focus Request directionalfocusrequest Initiated 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. Yes Yes
linearfocusrequest Initiated 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. Yes Yes
palettefocusrequest Initiated 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. Yes Yes
toolbarfocusrequest Initiated 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. Yes Yes
Manipulation Request moverequest Initiated 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. Yes Yes
panrequest Initiated 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. Yes Yes
rotationrequest Initiated when the user agent sends a rotation request to the web application with accompanying origin x/y values and a rotation value in degrees. Yes Yes
zoomrequest Initiated when the user agent sends a zoom request to the web application with accompanying origin x/y values and the zoom scale factor. Yes Yes
Scroll Request scrollrequest Initiated 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. Yes Yes
ValueChange Request valuechangerequest Initiated when the user agent sends a value change request to the web application. Used on custom range controls like sliders, carousels, etc. Yes Yes

Internet Explorer-specific events

[edit]

In addition to the common (W3C) 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.

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 (on the moving Element). Yes Yes
dragstart ondragstart Fires when a mouse drag begins (on the moving Element). Yes Yes
dragenter ondragenter Fires when something is dragged onto an area (on the target Element). Yes Yes
dragover ondragover Fires when a drag is held over an area (on the target Element). Yes Yes
dragleave ondragleave Fires when something is dragged out of an area (on the target Element). Yes Yes
dragend ondragend Fires when a mouse drag ends (on the moving Element). Yes Yes
drop ondrop Fires when a mouse button is released over a valid target during a drag (on the target Element). 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 the readystatechange event for the XMLHttpRequest object. Mozilla also supports the beforeunload event using the traditional event registration method (DOM Level 0). 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

[edit]

In addition to the common (W3C) events, Mozilla defined a set of events that work only with XUL elements.[citation needed]

Category Type Attribute Description Bubbles Cancelable
Mouse DOMMouseScroll DOMMouseScroll Fires when the mouse wheel is moved, causing the content to scroll. Yes Yes
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. Yes 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

Other events

[edit]

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). However, DOMContentLoaded has been added to the HTML 5 specification.[13] The DOMContentLoaded event was also implemented in the Webkit rendering engine build 500+.[14][15] This correlates to all versions of Google Chrome and Safari 3.1+. DOMContentLoaded is also implemented in Internet Explorer 9.[16]

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

Event flow

[edit]

Consider the situation when two event targets participate in a tree. Both have event listeners 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.[17]

W3C takes a middle position in this struggle.[18]: §1.2 

According to the W3C, events go through three phases when an event target participates in a tree:

  1. The capture phase: the event travels down from the root event target to the target of an event
  2. The target phase: the event travels through the event target
  3. The bubble phase (optional): the event travels back up from the target of an event to the root event target. The bubble phase will only occur for events that bubble (where event.bubbles == true)

You can find a visualization of this event flow at https://domevents.dev

Stopping events

[edit]

While an event is travelling through event listeners, the event can be stopped with event.stopPropagation() or event.stopImmediatePropagation()

  • event.stopPropagation(): the event is stopped after all event listeners attached to the current event target in the current event phase are finished
  • event.stopImmediatePropagation(): the event is stopped immediately and no further event listeners are executed

When an event is stopped it will no longer travel along the event path. Stopping an event does not cancel an event.

Legacy mechanisms to stop an event

[edit]
  • Set the event.cancelBubble to true (Internet Explorer)
  • Set the event.returnValue property to false

Canceling events

[edit]

A cancelable event can be canceled by calling event.preventDefault(). Canceling an event will opt out of the default browser behaviour for that event. When an event is canceled, the event.defaultPrevented property will be set to true. Canceling an event will not stop the event from traveling along the event path.

Event object

[edit]

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
Name Type Description
type DOMString The name of the event (case-insensitive in DOM level 2 but case-sensitive in DOM level 3 [19]).
target EventTarget Used to indicate the EventTarget to which the event was originally dispatched.
currentTarget EventTarget Used to indicate the EventTarget whose EventListeners are currently being processed.
eventPhase unsigned short Used to indicate which phase of event flow is currently being evaluated.
bubbles boolean Used to indicate whether or not an event is a bubbling event.
cancelable boolean Used to indicate whether or not an event can have its default action prevented.
timeStamp DOMTimeStamp 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.

Event handling models

[edit]

DOM Level 0

[edit]

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

Inline model

[edit]

In the inline model,[20] 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.

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Inline Event Handling</title>
</head>
<body>

	<h1>Inline Event Handling</h1>

	<p>Hey <a href="http://www.example.com" onclick="triggerAlert('Joe'); return false;">Joe</a>!</p>

	<script>
		function triggerAlert(name) {
			window.alert("Hey " + name);
		}
	</script>
</body>
</html>

One common misconception[citation needed] 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 () {
	triggerAlert('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

[edit]

In the traditional model,[21] 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:

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Traditional Event Handling</title>
</head>

<body>
	<h1>Traditional Event Handling</h1>
	
	<p>Hey Joe!</p>

	<script>
		var triggerAlert = function () {
			window.alert("Hey Joe");
		};
		
		// Assign an event handler
		document.onclick = triggerAlert;
		
		// Assign another event handler
		window.onload = triggerAlert;
		
		// Remove the event handler that was just assigned
		window.onload = null;
	</script>
</body>
</html>

To add parameters:

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

Inner functions preserve their scope.

DOM Level 2

[edit]

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

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

Some useful things to know :

  • To prevent an event from bubbling, 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 the traditional model

[edit]
<!doctype html>
<html lang="en">
<head>
     <meta charset="utf-8">
     <title>DOM Level 2</title>
</head>

<body>
     <h1>DOM Level 2</h1>
     
     <p>Hey Joe!</p>
     
     
     <script>
          var heyJoe = function () {
               window.alert("Hey Joe!");
          }
          
          // Add an event handler
          document.addEventListener( "click", heyJoe, true );  // capture phase
          
          // Add another event handler
          window.addEventListener( "load", heyJoe, false );  // bubbling phase
          
          // Remove the event handler just added
          window.removeEventListener( "load", heyJoe, false );
     </script>

</body>
</html>

Internet Explorer-specific model

[edit]

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,[22] and Internet Explorer 11 deletes its support for Microsoft-specific model.[23]

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 the old Internet Explorer-specific model

[edit]
<!doctype html>
<html lang="en">
<head>
     <meta charset="utf-8">
     <title>Internet Explorer-specific model</title>
</head>
<body>
     <h1>Internet Explorer-specific model</h1>

     <p>Hey Joe!</p>

     <script>
          var heyJoe = function () {
               window.alert("Hey Joe!");
          }
          
          // Add an event handler
          document.attachEvent("onclick", heyJoe);
          
          // Add another event handler
          window.attachEvent("onload", heyJoe);
          
          // Remove the event handler just added
          window.detachEvent("onload", heyJoe);
     </script>

</body>
</html>

References

[edit]

Further reading

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
A DOM event is a signal dispatched by the (DOM) to notify applications of significant occurrences, such as user interactions (e.g., clicks or key presses), system changes (e.g., network activity or low battery), or document modifications, enabling dynamic responses in web pages and applications. These events are represented as objects implementing the Event interface, which provides essential properties like type (indicating the event category), target (the originating element), and bubbles (whether the event propagates upward), along with methods such as preventDefault() to cancel default behaviors and stopPropagation() to halt further dissemination. The DOM event system, standardized as part of the platform-neutral DOM specification, evolved from early versions in DOM Level 2 (2000) to the current living standard maintained by , emphasizing a generic mechanism for event registration and handling across languages and environments. Event targets, which include elements, documents, and windows, implement the EventTarget interface to manage listeners via methods like addEventListener(), allowing multiple handlers to be attached without overwriting each other, unlike older inline attributes (e.g., onclick). Events propagate through the DOM tree in three phases: capturing (downward from root to target), at the target (where the event originates), and bubbling (upward to ancestors), with the bubbling phase enabled by default for most events to facilitate delegated handling. Common event types encompass events (e.g., click, keydown under the UI Events specification), and pointer events, keyboard events, and custom events via the CustomEvent interface for application-specific signals. This architecture ensures interoperability in web browsers while supporting advanced features like touch interactions and animation timelines.

Overview

Definition and Purpose

In the Document Object Model (DOM), events are objects that represent signals of "interesting changes" occurring in the document, such as user interactions like clicks or key presses, or browser-initiated actions like page loading. These events are based on the Event interface and are dispatched by the or applications to notify code of state changes that may impact execution. The primary purpose of DOM events is to enable the creation of dynamic and interactive web applications by allowing JavaScript to detect and respond to these signals in real time, thereby facilitating user experiences without requiring full page reloads. This mechanism supports the development of responsive interfaces where actions like form submissions or animations can be handled asynchronously on the client side. Key characteristics of DOM events include their asynchronous nature, meaning they occur unpredictably in response to external triggers; their dispatch to specific target nodes within the DOM ; and their ability to propagate through phases, such as capturing from ancestors to the target or bubbling from the target to ancestors, depending on the event's configuration. These features ensure efficient handling across the document structure while allowing developers to as needed. For instance, when a user clicks a element, a 'click' event is dispatched to that element, which can then trigger an associated handler to modify the content of a nearby , such as updating its text to reflect the interaction. This illustrates how bridge user input with programmatic responses in a structured manner.

History and Evolution

The origins of DOM events trace back to the mid-1990s with the introduction of "DOM Level 0" events, a non-standardized mix of HTML document functionalities implemented in Netscape Navigator 3.0 (released in August 1996) and Microsoft Internet Explorer 3.0 (released in August 1996). These early implementations supported basic event handling through inline attributes (e.g., onclick handlers in HTML) and proprietary scripting models, enabling simple interactions like mouse clicks and form submissions without a formal specification. This ad-hoc approach, while innovative for dynamic web pages, led to inconsistencies across browsers during the initial "browser wars." Standardization efforts began with the W3C's DOM Level 2 Events specification, published as a Recommendation on November 13, 2000, which introduced the addEventListener method for registering event handlers and defined event flow with capturing and bubbling phases to improve interoperability. Building on this, the W3C's DOM Level 3 Events working draft (initially released in 2000 and updated through the 2010s, though never advanced to Recommendation status) expanded support for advanced features, including detailed keyboard events via the KeyboardEvent interface and the ability to create custom events for specialized use cases; its concepts were later incorporated into successor specifications like UI Events. A key milestone came in 2011 with Internet Explorer 9, which adopted W3C DOM Level 2 standards, including event capture support, marking Microsoft's shift toward compliance and reducing cross-browser fragmentation. In the , the WHATWG's DOM Living Standard, initiated around 2012 as part of ongoing evolution, has unified and continuously updated event specifications to align with real-world browser implementations. This living approach facilitated the of inefficient legacy mutation events in favor of the MutationObserver API, introduced in 2012 to efficiently monitor DOM changes without performance overhead. Further integrations include the Pointer Events API (first standardized in 2013 for unified input handling across devices) and the Web Animations API (initial working draft in 2013, with key features maturing by 2016 for synchronized timing and scripting). The 2013 fork of Google's Blink rendering engine from enhanced cross-browser consistency, as Blink powers Chrome and , accelerating adoption of these standards. As of 2025, major browsers provide full support for DOM Level 3 and event specifications, with comprehensive compatibility for core methods like addEventListener across Chrome, , , and Edge. Recent focus has shifted toward , exemplified by the W3C's 1.2 Recommendation (June 2023), which enhances event notifications for assistive technologies through attributes like aria-live and improved focus management in the DOM. Ongoing efforts emphasize performance optimizations to support complex web applications while maintaining .

Event Types

User Interface and Device Events

User interface (UI) and device events in the Document Object Model (DOM) encompass a set of standardized events that capture interactions between users and the web page's visual elements, as well as changes in the document or window state. These events are primarily defined in the W3C UI Events specification, which extends the core DOM Event objects to support user interactions via input devices and interface modifications. UI events such as load, unload, error, abort, resize, and scroll are triggered by asynchronous or synchronous changes in the document, window, or element states, rather than direct user input. The load event fires when a resource, such as an image or the entire document, finishes loading successfully, targeting the Window, Document, or Element interfaces without bubbling or cancelability. Conversely, the unload event occurs synchronously when a resource is being removed or the page is navigated away from, also without bubbling. The error event signals a failure in resource loading, such as a broken image, and is asynchronous with no bubbling. Similarly, abort is dispatched synchronously when loading is intentionally stopped, like by user cancellation. The resize event, which does not bubble, is triggered when the browser window or document view dimensions change, allowing scripts to adjust layouts dynamically. The scroll event fires continuously as the user scrolls content, targeting elements with overflow, to enable smooth interactions like infinite scrolling implementations. Mouse events provide detailed tracking of cursor-based interactions, forming a foundational layer for pointer input in desktop environments. Defined under the MouseEvent interface in the UI Events specification, these include click, dblclick, mousedown, mouseup, mousemove, , mouseout, mouseenter, and mouseleave, all of which are synchronous and target Element nodes. The click event bubbles and is cancelable, dispatched upon a primary button press and release in the same location, often triggering activation behaviors like link navigation. Dblclick follows a similar pattern but for double-clicks, without a default action beyond bubbling. Mousedown and mouseup capture button presses and releases, both bubbling and cancelable to influence actions like drag initiation. Mousemove bubbles during pointer movement, enabling real-time tracking. Relatedly, and mouseout bubble when the pointer enters or exits an element, while non-bubbling mouseenter and mouseleave focus on boundary crossings for efficient hover effects. Key properties include clientX and clientY, which provide viewport-relative coordinates for precise positioning. Modifier flags like altKey, a boolean indicating if the Alt key is held, allow detection of combined inputs such as Ctrl+click. Keyboard events facilitate text and shortcut handling, using the KeyboardEvent interface to identify pressed keys without relying on character output. The primary events are keydown and keyup, both synchronous, bubbling, and cancelable, targeting Element nodes. Keydown fires when a key is pressed, potentially triggering default actions like inserting text or navigating, while keyup occurs on release with no default action. The deprecated keypress event, once used for character input, is no longer recommended in favor of keydown for broader compatibility, as it conflated key presses with printable characters. Essential properties include key, a DOMString representing the semantic meaning (e.g., "Enter" or "a"), and code, which identifies the physical key location (e.g., "KeyA" regardless of layout). Modifier properties like altKey extend to keyboard contexts for detecting combinations such as . Focus events manage element activation for and navigation, implemented via the FocusEvent interface. These include focus, blur, focusin, and focusout, all synchronous and non-cancelable, targeting or Element nodes. Focus and blur do not bubble, firing when an element receives or loses focus, such as via tabbing or clicking. In contrast, bubbling focusin and focusout provide notification to ancestors, useful for form validation on field entry. For modern multi-device support, touch and pointer events address mobile and stylus inputs, with pointer events offering a unified model. Touch events, defined in the Touch Events specification, include touchstart, touchmove, touchend, and touchcancel, all targeting Element nodes and cancelable except touchcancel. Touchstart fires on initial contact, touchmove during movement, touchend on release, and touchcancel when interrupted, such as by system gestures. However, the Pointer Events specification supersedes separate handling by providing hardware-agnostic events like pointerdown, pointermove, pointerup, pointerover, pointerout, pointerenter, pointerleave, and pointercancel, which map mouse, touch, and pen inputs to a single interface. These events are synchronous, bubble (except enter/leave variants), and include properties like pointerId for unique pointer tracking (e.g., multi-touch points) and pressure (0 to 1 scale) for stylus force sensitivity. As of October 2025, Pointer Events Level 3 (Candidate Recommendation) introduces enhancements for low-latency and precise input, including the pointerrawupdate event for high-frequency raw pointer movements (non-cancelable, secure contexts only), methods getCoalescedEvents() to retrieve batched events and getPredictedEvents() for speculative future events, and properties such as coalescedEvents and predictedEvents sequences in event initialization. These features support advanced applications like real-time gaming by reducing input lag and improving prediction accuracy. By unifying inputs—e.g., a touch gesture emulating mouse drag—pointer events simplify code for cross-device applications, such as drawing apps that work seamlessly on touchscreens or mice, while allowing pointerType ("touch", "mouse", "pen") for device-specific logic when needed.

Input and Media Events

Input and media events in the Document Object Model (DOM) provide mechanisms for handling user interactions with form controls and multimedia elements, enabling dynamic responses to data entry, file transfers, content manipulation, and playback states. These events are distinct from general user interface events, as they specifically address form submission, value changes, drag-and-drop operations, clipboard actions, media loading and playback, and text composition for input methods. Defined primarily in the HTML Living Standard and UI Events specifications, they allow developers to validate inputs, manage file uploads, control media playback, and support international text entry without relying on basic device interactions. Form events target interactive elements like <input>, <select>, <textarea>, and <form>, firing in response to user modifications or submissions. The submit event is dispatched on a <form> element when the form is submitted, such as by clicking a submit button or pressing Enter in a focused input; it is cancelable to prevent submission if validation fails. The reset event fires on a <form> when the form is reset, restoring controls to their initial values, and is also cancelable. The change event triggers on form controls when their value changes and the element loses focus, useful for detecting completed edits in text fields or selections. In contrast, the input event fires synchronously and bubbles whenever the value of an <input>, <select>, or <textarea> changes due to user action, providing real-time feedback such as live validation. The invalid event occurs on form controls when constraint validation fails, like required fields left empty, aiding client-side error handling. Finally, the select event is fired on text-based controls when a user selects text within them, allowing access to the selected range via the selectionStart and selectionEnd properties. Drag-and-drop events facilitate moving data between elements or from external sources, using the DragEvent interface and a dataTransfer object to carry payloads like text, , or files. The sequence begins with dragstart on the source element, where developers set data via dataTransfer.setData() and specify allowed effects (e.g., "copy" or "move"); this event is cancelable to abort the operation. As dragging proceeds, drag fires repeatedly on the source, allowing dynamic updates. On potential drop targets, dragenter signals entry, followed by dragover which must have its default prevented (via preventDefault()) to allow dropping, and where dropEffect can be set for visual feedback. Dragleave indicates exit from a target. The drop event on the target element provides read-only access to dataTransfer for retrieving data or files, and is cancelable. The operation ends with dragend on the source, regardless of success. The dataTransfer object supports formats like "text/plain" or "Files", enabling scenarios such as uploading dragged images. Clipboard events handle copy, cut, and paste operations, providing access to the clipboardData property of type DataTransfer for reading or modifying transferred content. The copy event fires on the or focused element when a user copies selected content (e.g., via Ctrl+C), allowing clipboardData.setData("text/html", customHTML) to alter what is copied. Similarly, cut triggers on editable elements during cut actions (e.g., Ctrl+X), where preventing default removes the selection after custom data is set. The paste event occurs on editable elements during paste (e.g., Ctrl+V), enabling retrieval of pasted text or files via clipboardData.getData("text") or clipboardData.files, and modification to sanitize input. These bubble and are cancelable, supporting secure content manipulation like preventing sensitive data copies. Media events apply to <audio> and <video> elements via the HTMLMediaElement interface, tracking loading, playback, and errors for seamless user experiences. Loading begins with loadstart, followed by progress for download updates; suspend indicates intentional pausing, while abort signals incomplete loading without error. Errors trigger error, and emptied fires when media is reset (e.g., after load()). Metadata availability is notified by loadedmetadata, and first-frame loading by loadeddata. Playback readiness is indicated by canplay (may buffer) and canplaythrough (smooth to end). Seeking starts with seeking and ends with seeked; timeupdate reports position changes. Playback controls include play (starts or resumes), pause (pauses), playing (resumes after stall), and waiting (buffering pause). Completion triggers ended, with stalled for unexpected data halts. Rate or volume adjustments fire ratechange or volumechange, respectively. Composition events support input method editors (IMEs) for non-Latin scripts, such as , by managing text assembly before final insertion. The compositionstart event fires when IME input begins, often displaying a candidate ; it is cancelable to suppress composition. Compositionupdate signals changes to the composed text, providing the current string via the data property for preview or correction. Compositionend indicates completion or cancellation, with final data available for insertion. These events target editable elements, integrate with input events (where InputEvent.isComposing is true during session), and ensure accurate handling of complex character entry. In practice, these events enable robust applications; for instance, the input event can validate format in real-time on a <input type="email"> field, displaying errors via invalid if constraints fail before submit. Drag-and-drop file uploads use drop to access dataTransfer.files and process images asynchronously, while paste on a rich retrieves clipboardData.getData("text/html") to insert formatted content safely. Media players listen for timeupdate to sync subtitles and ended to autoplay next tracks, ensuring smooth streaming.

Legacy and Vendor-Specific Events

Legacy and vendor-specific events in the DOM refer to those that are either deprecated by standards bodies or implemented uniquely by particular browsers, often leading to compatibility issues and performance drawbacks in modern web development. These events were introduced in early browser iterations to handle specific interactions but have been phased out in favor of standardized alternatives that offer better efficiency and cross-browser consistency. Among the deprecated events, the keypress event, originally part of the legacy DOM Level 0 events, was used to detect printable key presses but is no longer recommended due to inconsistencies in handling non-character keys across browsers. It has been replaced by keydown and keyup events for broader key detection or the beforeinput event for text input handling. Similarly, mutation events such as DOMSubtreeModified, DOMNodeInserted, and DOMNodeRemoved, defined in the DOM Level 2 specification, monitored changes to the DOM tree but suffered from severe performance issues, as they fired synchronously during modifications, potentially slowing down scripts and causing excessive event propagation overhead. These were deprecated in DOM Level 3 Events, with the MutationObserver API introduced in 2012 as an asynchronous, more efficient replacement that batches notifications and avoids blocking the main thread. Internet Explorer introduced several proprietary events that were not part of the W3C standards, complicating cross-browser development until the browser's discontinuation after version 11. The onpropertychange event fired whenever a property of an or its style object changed, serving as an early mechanism for detecting dynamic updates, but it lacked the precision of modern attribute change observers and was prone to firing unnecessarily. Likewise, the onlosecapture event notified when an element lost mouse capture, a feature tied to IE's setCapture method, which has no direct equivalent in standards-compliant browsers today. The attachEvent method, used in IE to register event handlers, followed a non-bubbling model unlike the standard addEventListener, and its use was phased out post-IE11 in favor of the unified EventTarget interface. Mozilla's (XML User Interface Language) framework, primarily for extensions and legacy add-ons, included events like popupshowing, which fired just before a popup menu was displayed to allow dynamic content adjustment, and command, which handled user interactions with XUL elements such as buttons. These events were confined to Mozilla-specific environments and are now largely obsolete following the of XUL-based add-ons in 57 (2017), with developers encouraged to migrate to WebExtensions using standard DOM events. Vendor-prefixed events from , such as webkitAnimationStart, webkitAnimationIteration, and webkitAnimationEnd, provided early support for in and older Chrome versions before . These prefixed variants ensured compatibility during the transition to unprefixed names like animationstart, but their use is discouraged today to promote adherence to the specification. Other niche proposals, like certain IndieWeb events for , remain non-standard and unadopted, highlighting the importance of sticking to W3C-recommended interfaces. The primary reasons for deprecating these events include performance bottlenecks, such as the synchronous firing of mutation events that could degrade DOM operations by orders of magnitude, and the fragmentation caused by vendor-specific implementations, which hindered web portability. For migration, developers should replace keypress with keydown or keyup for key handling, adopt for DOM (observing specific node types and attributes without hits), use ResizeObserver instead of the legacy window.onresize for element resizing, and universally employ addEventListener over attachEvent. These shifts align with modern standards, improving efficiency and maintainability in web applications.

Event Propagation

Propagation Phases

DOM event propagation occurs in three distinct phases as the event travels through the DOM tree, allowing listeners on ancestor elements to respond to events originating from descendant targets. The first phase is the capturing phase (also known as the capture or trickling phase), where the event starts at the root of the document (typically the Document node) and propagates downward through the ancestors toward the target element. During this phase, event listeners registered with capturing enabled are invoked in tree order, from the outermost ancestor to the innermost one closest to the target. The second phase is the target phase (or at-target phase), in which the event arrives at and is processed by the target element—the node on which the event was originally dispatched. Here, all event listeners on the target, regardless of whether they are set for capturing or bubbling, are invoked. This phase is crucial as it represents the primary point of event handling at the intended destination. Following the target phase, the bubbling phase begins, where the event travels back up the DOM tree from the target through its ancestors toward the root, invoking bubbling listeners in reverse tree order (from innermost to outermost). Most events bubble by default if their bubbles property is set to true, enabling event delegation patterns where parent elements can handle events from children. To participate in the capturing phase, developers specify the third parameter as true (or {capture: true} in options) when calling addEventListener(). The full event path, which determines the sequence of nodes traversed during , can be retrieved using the composedPath() method on the event object; this path includes nodes from shadow DOM trees in modern implementations, allowing events to cross shadow boundaries unless restricted by a closed shadow root. Only trusted events—those generated by the in response to user actions, with isTrusted set to true—undergo full propagation and can trigger default actions; synthetic events created via script (e.g., using new Event() and dispatchEvent()) propagate through the phases but lack the isTrusted flag and may not invoke certain browser behaviors. For example, consider a click event on a nested <div> element within a :

html

<div id="grandparent"> <div id="parent"> <div id="child">Click me</div> </div> </div>

<div id="grandparent"> <div id="parent"> <div id="child">Click me</div> </div> </div>

If capturing listeners are attached to all three elements, the click event first triggers the grandparent's capturing listener, then the 's, followed by the target's (child) listeners in the target phase, and finally bubbles up through the and grandparent's bubbling listeners. This traversal ensures comprehensive handling across the without direct attachment to every potential target.

Controlling Propagation

In DOM events, propagation can be halted or modified using methods available on the Event interface to control how the event travels through the DOM tree. The stopPropagation() method prevents further propagation of the event in the current phase, stopping it from reaching subsequent elements in the bubbling or capturing phase without affecting other listeners on the same element. For finer control, stopImmediatePropagation() not only halts propagation to other elements but also prevents any remaining event listeners on the current element from being invoked during the same phase. These methods are invoked within an event handler, typically passed as the first argument to the callback function registered via addEventListener(). Default actions associated with certain events, such as form submission or link navigation, can be canceled using the preventDefault() method if the event is designated as cancelable, which can be verified by checking the cancelable property on the Event object. For instance, in a click event on an anchor element, calling event.preventDefault() within the handler blocks the browser from following the link's URL. Similarly, for a submit event on a form, this method prevents the form data from being sent to the server. Only events with cancelable set to true respond to this method; attempting it on non-cancelable events has no effect. Legacy mechanisms from earlier event models provide alternative ways to control propagation and defaults, though they are deprecated in modern standards. In DOM Level 0 event handling, such as inline handlers like onclick="handler()", returning false from the handler function both cancels the default action and stops event bubbling. In the proprietary event model, setting event.returnValue = false achieves a similar effect of preventing the default action. These approaches were common in pre-DOM Level 2 environments but are now superseded by standard methods for cross-browser compatibility. For performance optimization in scenarios involving frequent events like touch or scroll, the passive option can be set to true when registering a listener via addEventListener(), indicating that the handler will not invoke preventDefault(). This allows browsers to implement faster event handling paths, particularly for non-cancelable events such as wheel or touchstart, without the overhead of checking for potential default cancellation. While it does not directly prevent bubbling, it ensures the event remains non-cancelable, enabling smoother scrolling and touch interactions on mobile devices. To stop a link from navigating upon click while allowing other behaviors:

javascript

document.querySelector('a').addEventListener('click', function(event) { event.preventDefault(); // Cancels the default navigation console.log('Link clicked, but no navigation occurred.'); });

document.querySelector('a').addEventListener('click', function(event) { event.preventDefault(); // Cancels the default navigation console.log('Link clicked, but no navigation occurred.'); });

This code attaches a listener to an anchor element and uses preventDefault() to block the hyperlink's default action.

Example: Stopping Bubbling to Parent

To prevent a child element's click event from triggering a parent's handler:

javascript

childElement.addEventListener('click', function(event) { event.stopPropagation(); // Halts bubbling to ancestors console.log('Click handled on child only.'); }); parentElement.addEventListener('click', function(event) { console.log('This will not fire if stopped on child.'); });

childElement.addEventListener('click', function(event) { event.stopPropagation(); // Halts bubbling to ancestors console.log('Click handled on child only.'); }); parentElement.addEventListener('click', function(event) { console.log('This will not fire if stopped on child.'); });

Here, stopPropagation() ensures the event does not bubble up to the parent, isolating the handling to the child element.

Event Object

Core Properties and Methods

The Event interface serves as the foundational object for all DOM events, providing a set of universal properties and methods that enable developers to inspect event details and control their behavior during dispatch. This generic structure ensures consistency across different event types, allowing event handlers to access core metadata regardless of the specific event category. Key properties of the Event object include several read-only attributes that describe the event's characteristics and context. The type property is a string specifying the event's name, such as "click" or "keydown", which identifies the kind of event being processed. The target property references the EventTarget to which the event was originally dispatched, typically the element where the interaction occurred. In contrast, the currentTarget property points to the EventTarget whose event listener is currently executing the handler, which may differ from the target during propagation. The eventPhase property is an unsigned short integer indicating the current phase of event propagation, with possible values defined as constants: NONE (0) for no active dispatch, CAPTURING_PHASE (1) during the capturing phase, AT_TARGET (2) at the target element, and BUBBLING_PHASE (3) during the bubbling phase. The bubbles property is a boolean that is true if the event is configured to bubble up through the DOM tree to ancestor elements. Similarly, the cancelable property is a boolean indicating whether the event's default action can be prevented via the preventDefault() method. The timeStamp property provides a DOMHighResTimeStamp value representing the time in milliseconds since the event was created, relative to the navigation start time. The defaultPrevented property is a boolean that becomes true after preventDefault() has been invoked on the event. Finally, the isTrusted property is a boolean that is true if the event was generated by the user agent (e.g., a genuine user interaction) rather than synthetically created by script. The Event interface also defines methods for managing event flow and default behaviors. The stopPropagation() method prevents the event from continuing to propagate to other elements in the DOM tree, halting both capturing and bubbling phases beyond the current point. The stopImmediatePropagation() method extends this by not only stopping propagation but also preventing any remaining event listeners on the current target from executing. The preventDefault() method, when called on a cancelable event, suppresses the browser's default action associated with the event, such as following a link on a "click" event. Developers can check if this has occurred using the defaultPrevented property, as there is no separate isDefaultPrevented() method in the standard interface. Additionally, the composedPath() method returns an array of EventTarget objects representing the full path of elements through which the event will or has propagated, useful for shadow DOM contexts. In practice, these properties and methods are accessed within an event handler function to inspect and respond to events dynamically. For example, a handler might log the event type and target element as follows:

javascript

element.addEventListener('click', function(event) { console.log('Event type:', event.type); // e.g., "click" console.log('Target element:', event.target); // e.g., <button> element });

element.addEventListener('click', function(event) { console.log('Event type:', event.type); // e.g., "click" console.log('Target element:', event.target); // e.g., <button> element });

This approach allows for targeted debugging and conditional logic based on event details. Specialized event interfaces, such as MouseEvent, extend these core elements with type-specific properties, while methods like stopPropagation() play a key role in controlling propagation as detailed elsewhere.

Specialized Event Interfaces

Specialized event interfaces in the DOM extend the base Event interface to provide additional properties and methods tailored to specific types of user interactions or network activities, enabling developers to access context-specific data such as coordinates, key values, or progress metrics. These extensions form a hierarchy where most user interface-related events inherit from UIEvent, which itself derives from Event, allowing for shared core properties like type, target, and timeStamp while adding category-unique attributes. The UIEvent interface serves as the foundation for events related to user interface interactions, such as mouse clicks or keyboard input. It includes the view property, which references the Window object associated with the event's context (defaulting to null), and the detail property, a long integer providing event-specific information, such as the click count in a mouse event (defaulting to 0). For instance, FocusEvent, which inherits from UIEvent, uses relatedTarget to indicate the element gaining or losing focus (defaulting to null). MouseEvent extends UIEvent to capture pointer interactions from mouse devices, adding properties for positional data and button states. Key attributes include screenX and screenY (long integers for coordinates relative to the screen, defaulting to 0), clientX and clientY (long integers for coordinates relative to the viewport, defaulting to 0), button (a short integer indicating the pressed button, ranging from 0 for left to 4 for auxiliary, defaulting to 0), buttons (an unsigned short bitmask of currently pressed buttons, defaulting to 0), and relatedTarget (an EventTarget for the secondary element involved, such as in mouseover events, defaulting to null). KeyboardEvent, also extending UIEvent, provides details for keyboard input. It features the key property (a DOMString representing the logical key value, such as "a" or "Shift"), code (a DOMString for the physical key location, like "KeyA" or "Digit1"), location (an unsigned long indicating the key's position: 0 for standard, 1 for left, 2 for right, 3 for numpad), repeat (a true if the key is being held down for repetition), and isComposing (a true during text composition, such as IME input). An example of usage involves extracting the key value in an event handler to determine the pressed character: if (event.key === 'Enter') { /* handle submission */ }. For touch-based interactions, TouchEvent extends UIEvent and manages multi-touch scenarios through lists of Touch objects. It includes touches (a TouchList of all current touch points on the surface), targetTouches (a TouchList of touches originating from the event target), and changedTouches (a TouchList of touches that triggered the event, such as new or ended points). Each Touch object provides coordinates like clientX/clientY (viewport-relative pixels, excluding scroll), pageX/pageY (viewport-relative including scroll), and screenX/screenY (screen-relative pixels). Handling might involve iterating over changedTouches to update positions for gestures, such as pinch-to-zoom. PointerEvent builds on MouseEvent to unify handling of mouse, pen, and touch inputs, adding device-agnostic properties for advanced input. These include pointerId (a long unique identifier for the pointer, defaulting to 0), width and height (doubles for contact geometry in CSS pixels, defaulting to 1), pressure (a float from 0 to 1 for applied pressure, defaulting to 0 or 0.5 when active), tiltX and tiltY (longs for tilt angles in degrees, ranging -90 to 90, defaulting to 0), and pointerType (a DOMString specifying "mouse", "pen", "touch", or empty). Network-related specialized interfaces include ProgressEvent, which extends Event for tracking data transfer and features loaded (bytes transferred since request start) and total (total expected bytes, if known). Similarly, CloseEvent, used in WebSocket connections, extends Event with wasClean (a boolean true if the connection closed orderly per protocol). This inheritance structure—Event as the root, with UIEvent branching to input-specific interfaces like MouseEvent, KeyboardEvent, and TouchEvent, and PointerEvent further extending MouseEvent—ensures consistent access to base event details while providing precise data for specialized handling.

Event Handling

Modern Registration Methods

In modern web development, the primary method for registering event listeners adheres to the standards defined by the DOM specification, utilizing the addEventListener() method on objects implementing the EventTarget interface. This approach supersedes legacy inline event handlers, offering greater flexibility, support for multiple listeners per event type, and precise control over listener behavior. The EventTarget interface serves as the foundational mechanism for event handling in the DOM, enabling objects such as Element, Document, and Window to register and dispatch events. It allows multiple event listeners to be attached to the same event type on a single target, facilitating modular code organization without overwriting previous registrations. The addEventListener() method appends a listener to the target's event listener list, while removeEventListener() removes a matching listener, ensuring clean management of event bindings. The syntax for addEventListener() is target.addEventListener(type, listener, options), where type is a case-sensitive specifying the event (e.g., "click"), listener is a function or an object implementing the EventListener interface via a handleEvent() method, and options is an optional object or for legacy capture mode. The options object provides advanced configuration: capture (, default false) determines if the listener triggers during the capturing phase of event ; passive (, default false) indicates that the listener will not call preventDefault(), optimizing for events like or touchstart (and is the default in some browsers for and touch events); once (, default false) automatically removes the listener after its first invocation; and signal (an AbortSignal from an AbortController) enables cancellation of the listener without explicit removal. This method returns undefined and does not throw errors if the listener is already registered, though duplicates may accumulate unless options differ. For custom events, developers can create instances using the CustomEvent constructor: new CustomEvent(type, options), where type is the event name and options includes a detail property to carry arbitrary data (e.g., objects or primitives) to the listener. These events are dispatched via the dispatchEvent() method on an EventTarget, triggering registered listeners synchronously. Custom events are useful for application-specific signaling, such as notifying components of user actions like completion. Best practices emphasize using addEventListener() over inline attributes (e.g., onclick) for , testability, and avoidance of global scope pollution. To prevent memory leaks, especially in long-lived applications or single-page apps, remove listeners explicitly with removeEventListener() when no longer needed, using named functions rather than anonymous ones for reliable matching. For performance-critical events like touch or scroll, set passive: true to allow the browser to optimize rendering without awaiting potential preventDefault() calls. Example: Adding a one-time click listener

javascript

const button = document.querySelector('button'); const handleClick = () => { console.log('Button clicked once'); }; button.addEventListener('click', handleClick, { once: true }); // After one click, the listener is automatically removed

const button = document.querySelector('button'); const handleClick = () => { console.log('Button clicked once'); }; button.addEventListener('click', handleClick, { once: true }); // After one click, the listener is automatically removed

Example: Dispatching a custom event

javascript

const loginEvent = new CustomEvent('userLogin', { detail: { userId: 123, timestamp: Date.now() } }); [document](/page/Document).dispatchEvent(loginEvent); // Listeners registered for 'userLogin' will receive the detail data

const loginEvent = new CustomEvent('userLogin', { detail: { userId: 123, timestamp: Date.now() } }); [document](/page/Document).dispatchEvent(loginEvent); // Listeners registered for 'userLogin' will receive the detail data

Historical Handling Models

The earliest approaches to handling DOM events, known as the DOM Level 0 model, emerged in the mid-1990s with browsers like and , predating formal W3C standards. This model included two primary methods: inline event handlers embedded directly in and script-based assignment to element properties. Inline handlers used attributes such as onclick="handleClick()" within tags, allowing simple execution in response to events like clicks or mouse movements. Similarly, the traditional script-based method assigned functions to DOM element properties prefixed with on, such as element.onclick = function() { /* code */ };, enabling dynamic attachment after page load. These techniques relied on browser-created arrays like document.images or document.forms for element access, limiting their scope to predefined collections without support for arbitrary DOM nodes. A key limitation of the DOM Level 0 model was its inability to attach multiple handlers to the same event on an element; assigning a new function to an on* or inline attribute would overwrite any existing one, restricting flexibility in complex applications. Additionally, event cancellation in this model typically required returning false from the handler function, which prevented default behaviors like form submission but offered no granular control over . The event object itself was often accessed implicitly or via a global event variable in some implementations, lacking . With the introduction of the DOM Level 2 Events specification in 2000, the addEventListener method provided a more robust alternative, allowing multiple handlers per event and introducing a useCapture for capturing phase support—features absent in Level 0. Early implementations of addEventListener(type, listener, useCapture) contrasted sharply with Level 0 by enabling event delegation and avoiding property overwrites, though the third defaulted to bubbling (false) and lacked modern options like passive or once. This method was designed for broader compatibility across EventTarget interfaces, moving beyond HTML-specific limitations. Microsoft Internet Explorer, from versions 5 to 10, diverged with its proprietary attachEvent method, which mirrored addEventListener in attaching handlers but omitted capture phase support entirely, restricting events to the bubbling phase only. Like DOM Level 0, attachEvent used a global event object rather than passing it as a parameter, and handlers fired in reverse attachment order. It allowed multiple handlers without overwriting, but early IE versions provided no direct bubbling control, relying on return false for basic cancellation similar to Level 0. All these historical models have been deprecated in favor of the standardized addEventListener method, which unifies behavior across modern browsers since Internet Explorer 11 and Edge. For migration, legacy code like element.onclick = handleClick; can be rewritten as element.addEventListener('click', handleClick);, preserving functionality while gaining support for multiple handlers and phases. Inline attributes remain functional for simple cases but are discouraged due to security risks like XSS vulnerabilities from dynamic content injection.

References

Add your contribution
Related Hubs
Contribute something
User Avatar
No comments yet.