Touch_event

DOM event

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

HTML events

Common events

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.

More information Category, Type ...

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

Touch events

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

More information Category, Type ...

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

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]

More information Category, Type ...

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

More information Category, Type ...

Internet Explorer-specific events

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.

More information Category, Type ...

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

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

More information Category, Type ...

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

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

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.

More information Name, Type ...
More information Name, Argument type ...

Event handling models

DOM Level 0

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

Inline model

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 doc>
<doc 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>
</doc>

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

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 doc>
<doc 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>
</doc>

To add parameters:

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

Inner functions preserve their scope.

DOM Level 2

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

More information Name, Description ...

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

<!doctype doc>
<doc 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>
</doc>

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

More information Name, Description ...

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

<!doctype doc>
<doc 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>
</doc>

References

  1. "DOM Standard". dom.spec.whatwg.org. Retrieved 2021-05-25.
  2. "JavaScript DOM Events". www.w3schools.com. Retrieved 2019-08-03.
  3. "Touch Events version 2 - W3C Editor's Draft". W3C. 14 November 2011. Retrieved 10 December 2011.
  4. "Apple using patents to undermine open standards again". opera.com. 9 December 2011. Retrieved 9 December 2011.
  5. Archived June 11, 2010, at the Wayback Machine
  6. "Which browsers support native DOMContentLoaded event? « Perfection Labs Development Tips". 29 June 2011. Archived from the original on 29 June 2011.{{cite web}}: CS1 maint: bot: original URL status unknown (link)
  7. "Test Drive Redirect". Archived from the original on 2010-05-08. Retrieved 2010-05-06.
  8. "Introduction to Events". Quirksmode.org. Retrieved 15 September 2012.
  9. "Document Object Model (DOM) Level 2 Events Specification". W3C. 13 November 2000. Retrieved 15 September 2012.
  10. "Early event handlers". Quirksmode.org. Retrieved 15 September 2012.
  11. "Traditional event registration model". Quirksmode.org. Retrieved 15 September 2012.
  12. "DOM Level 3 Events support in IE9". Microsoft. March 26, 2010. Retrieved 2010-03-28.
  13. "Compatibility changes in IE11 Preview". Microsoft. September 9, 2013. Retrieved 2013-10-05.

Further reading


Share this article:

This article uses material from the Wikipedia article Touch_event, and is written by contributors. Text is available under a CC BY-SA 4.0 International License; additional terms may apply. Images, videos and audio are available under their respective licenses.