DOM Event
   HOME

TheInfoList



OR:

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. Client-side scripting languages like
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
,
JScript JScript is Microsoft's legacy dialect of the ECMAScript standard that is used in Microsoft's Internet Explorer web browser and HTML Applications, and as a standalone Windows scripting language. JScript is implemented as an Active Scripting eng ...
,
VBScript VBScript (Microsoft Visual Basic Scripting Edition) is a deprecated programming language for scripting on Microsoft Windows using Component Object Model (COM), based on classic Visual Basic and Active Scripting. It was popular with system admi ...
, and
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
can register various event handlers or listeners on the element nodes inside a DOM tree, such as in
HTML Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets ( ...
,
XHTML Extensible HyperText Markup Language (XHTML) is part of the family of XML markup languages which mirrors or extends versions of the widely used HyperText Markup Language (HTML), the language in which Web pages are formulated. While HTML, pr ...
, 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 Historically, like DOM, the event models used by various
web browser A web browser, often shortened to browser, is an application for accessing websites. When a user requests a web page from a particular website, the browser retrieves its files from a web server and then displays the page on the user's scr ...
s had some significant differences which caused compatibility problems. To combat this, the event model was standardized by the
World Wide Web Consortium The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web. Founded in 1994 by Tim Berners-Lee, the consortium is made up of member organizations that maintain full-time staff working together in ...
(W3C) in DOM Level 2.


Events


HTML events


Common events

There is a huge collection of events that can be generated by most element nodes: *
Mouse A mouse (: mice) is a small rodent. Characteristically, mice are known to have a pointed snout, small rounded ears, a body-length scaly tail, and a high breeding rate. The best known mouse species is the common house mouse (''Mus musculus'' ...
events. *
Keyboard Keyboard may refer to: Text input * Keyboard, part of a typewriter * Computer keyboard ** Keyboard layout, the software control of computer keyboards and their mapping ** Keyboard technology, computer keyboard hardware and firmware Music * Mus ...
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 (used by
XMLHttpRequest XMLHttpRequest (XHR) is an API in the form of a JavaScript object whose methods transmit HTTP requests from a web browser to a web server. The methods allow a browser-based application to send requests to the server after page loading is complet ...
and File API). Note that the event classification above is not exactly the same as W3C's classification. 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 Mozilla is a free software community founded in 1998 by members of Netscape. The Mozilla community uses, develops, publishes and supports Mozilla products, thereby promoting free software and open standards. The community is supported institution ...
and
Opera Opera is a form of History of theatre#European theatre, Western theatre in which music is a fundamental component and dramatic roles are taken by Singing, singers. Such a "work" (the literal translation of the Italian word "opera") is typically ...
support ''DOMAttrModified'', ''DOMNodeInserted'', ''DOMNodeRemoved'' and ''DOMCharacterDataModified''. Chrome and
Safari A safari (; originally ) is an overland journey to observe wildlife, wild animals, especially in East Africa. The so-called big five game, "Big Five" game animals of Africa – lion, African leopard, leopard, rhinoceros, African elephant, elep ...
support these events, except for ''DOMAttrModified''.


Touch events

Web browsers running on touch-enabled devices, such as Apple's
iOS Ios, Io or Nio (, ; ; locally Nios, Νιός) is a Greek island in the Cyclades group in the Aegean Sea. Ios is a hilly island with cliffs down to the sea on most sides. It is situated halfway between Naxos and Santorini. It is about long an ...
and Google's Android, generate additional events. In the
W3C The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web. Founded in 1994 by Tim Berners-Lee, the consortium is made up of member organizations that maintain full-time staff working together in ...
draft recommendation, a TouchEvent delivers a TouchList of Touch locations, the
modifier key In computing, a modifier key is a special key (or combination) on a computer keyboard that temporarily modifies the normal action of another key when pressed together. By themselves, modifier keys usually do nothing; that is, pressing any of the , ...
s 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 An apple is a round, edible fruit produced by an apple tree (''Malus'' spp.). Fruit trees of the orchard or domestic apple (''Malus domestica''), the most widely grown in the genus, are agriculture, cultivated worldwide. The tree originated ...
didn't join this working group, and delayed W3C recommendation of its Touch Events Specification by disclosing
patents A patent is a type of intellectual property that gives its owner the legal right to exclude others from making, using, or selling an invention for a limited period of time in exchange for publishing an sufficiency of disclosure, enabling discl ...
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.


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: * 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.


Internet Explorer-specific events

In addition to the common (W3C) events, two major types of events are added by
Internet Explorer Internet Explorer (formerly Microsoft Internet Explorer and Windows Internet Explorer, commonly abbreviated as IE or MSIE) is a deprecation, retired series of graphical user interface, graphical web browsers developed by Microsoft that were u ...
. Some of the events have been implemented as
de facto standard A ''de facto'' standard is a custom or convention that is commonly used even though its use is not required. is a Latin phrase (literally " of fact"), here meaning "in practice but not necessarily ordained by law" or "in practice or actuality, ...
s by other browsers. *
Clipboard A clipboard is a thin, rigid writing board with a clip at the top for holding paper in place. A clipboard is typically used to support paper with one hand while writing on it with the other, especially when other writing surfaces are not avail ...
events. * Data binding events. Note that Mozilla, Safari and Opera also support the readystatechange event for the
XMLHttpRequest XMLHttpRequest (XHR) is an API in the form of a JavaScript object whose methods transmit HTTP requests from a web browser to a web server. The methods allow a browser-based application to send requests to the server after page loading is complet ...
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

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


Other events

For Mozilla and Opera 9, there are also undocumented events known as ''DOMContentLoaded'' and ''DOMFrameContentLoaded'' which fire when the DOM content is loaded. These are different from "load" as they fire before the loading of related files (e.g., images). However, DOMContentLoaded has been added to the
HTML 5 HTML5 (Hypertext Markup Language 5) is a markup language used for structuring and presenting hypertext documents on the World Wide Web. It was the fifth and final major HTML version that is now a retired World Wide Web Consortium (W3C) recommend ...
specification. The DOMContentLoaded event was also implemented in the
Webkit WebKit is a browser engine primarily used in Apple's Safari web browser, as well as all web browsers on iOS and iPadOS. WebKit is also used by the PlayStation consoles starting with the PS3, the Tizen mobile operating systems, the Amazon K ...
rendering engine build 500+. This correlates to all versions of
Google Chrome Google Chrome is a web browser developed by Google. It was first released in 2008 for Microsoft Windows, built with free software components from Apple WebKit and Mozilla Firefox. Versions were later released for Linux, macOS, iOS, iPadOS, an ...
and
Safari A safari (; originally ) is an overland journey to observe wildlife, wild animals, especially in East Africa. The so-called big five game, "Big Five" game animals of Africa – lion, African leopard, leopard, rhinoceros, African elephant, elep ...
3.1+. DOMContentLoaded is also implemented in
Internet Explorer 9 Internet Explorer 9 or IE9 (officially Windows Internet Explorer 9) is the ninth major version of the Internet Explorer web browser for Windows. It was released by Microsoft on March 14, 2011, as the successor to Internet Explorer 8. Microsoft re ...
. Opera 9 also supports the Web Forms 2.0 events ''DOMControlValueChanged'', ''invalid'', ''forminput'' and ''formchange''.


Event flow

Consider the situation when two event targets participate in
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 The 1990s releases of the Netscape (web browser), Netscape line referred to as Netscape Navigator were a series of now discontinued web browsers. from versions 1 to 4.08. It was the Core product, flagship product of the Netscape, Netscape Comm ...
. * Trigger the elements from inner to outer ( event bubbling). This model is implemented in Internet Explorer and other browsers. W3C takes a middle position in this struggle. According to the W3C, events go through three phases when an event target participates in a tree: # The capture phase: the event travels down from the root event target to the target of an event # The target phase: the event travels through the event target # 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

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

* Set the event.cancelBubble to true (Internet Explorer) * Set the event.returnValue property to false


Canceling events

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

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 handling models


DOM Level 0

This event handling model was introduced by
Netscape Navigator The 1990s releases of the Netscape (web browser), Netscape line referred to as Netscape Navigator were a series of now discontinued web browsers. from versions 1 to 4.08. It was the Core product, flagship product of the Netscape, Netscape Comm ...
, 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 An alert dialog box is a special dialog box that is displayed in a graphical user interface when something unexpected occurred that requires immediate user action. The typical alert dialog provides information in a separate box to the user, af ...
with the message "Hey Joe" appears after the
hyperlink In computing, a hyperlink, or simply a link, is a digital reference providing direct access to Data (computing), data by a user (computing), user's point and click, clicking or touchscreen, tapping. A hyperlink points to a whole document or to ...
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 The first engines for JavaScript were mere interpreters of the source code, but all relevant modern engines use just-in-time compilation for improved performance. JavaScript engines are typically developed by web browser vendors, and every maj ...
of the browser creates an
anonymous function In computer programming, an anonymous function (function literal, expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for const ...
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 = (function (name) (name)); Inner functions preserve their scope.


DOM Level 2

The W3C designed a more flexible event handling model in DOM Level 2. 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 Mozilla is a free software community founded in 1998 by members of Netscape. The Mozilla community uses, develops, publishes and supports Mozilla products, thereby promoting free software and open standards. The community is supported institution ...
,
Opera Opera is a form of History of theatre#European theatre, Western theatre in which music is a fundamental component and dramatic roles are taken by Singing, singers. Such a "work" (the literal translation of the Italian word "opera") is typically ...
,
Safari A safari (; originally ) is an overland journey to observe wildlife, wild animals, especially in East Africa. The so-called big five game, "Big Five" game animals of Africa – lion, African leopard, leopard, rhinoceros, African elephant, elep ...
, Chrome and
Konqueror Konqueror is a Free and open-source software, free and open-source web browser and file manager that provides World Wide Web, web access and file viewer, file-viewer functionality for file systems (such as local files, files on a remote FTP ser ...
.


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. 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 Internet Explorer (formerly Microsoft Internet Explorer and Windows Internet Explorer, commonly abbreviated as IE or MSIE) is a deprecation, retired series of graphical user interface, graphical web browsers developed by Microsoft that were u ...
and Trident based browsers (e.g.
Maxthon Maxthon (, formerly named ''MyIE2'') is a freeware web browser, created by JeffChen in Singapore. It is available for Microsoft Windows, Windows, macOS, Linux, and as ''Maxthon Mobile'' for Android (operating system), Android, iOS, and Windows P ...
, Avant Browser).


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

Internet Explorer-specific model

Internet Explorer-specific model

Hey Joe!


References


Further reading

* Deitel, Harvey. (2002). ''Internet and World Wide Web: how to program'' (Second Edition). * The Mozilla Organization. (2009)
DOM Event Reference
Retrieved August 25, 2009. * Quirksmode (2008)

Retrieved November 27, 2008. * http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/


External links


Document Object Model (DOM) Level 2 Events Specification

Document Object Model (DOM) Level 3 Events Working Draft



UI Events Working Draft

Pointer Events W3C Candidate Recommendation

MSDN PointerEventdomevents.dev - A visualizer to learn about DOM Events through exploration

JS fiddle for Event Bubbling and Capturing
{{DEFAULTSORT:Dom Events World Wide Web Consortium standards Application programming interfaces Events (computing)