DOM events

DOM (Document Object Model) events allow event-driven programming languages like JavaScriptJScriptECMAScriptVBScript and Java to register various event handlers/listeners on the element nodes inside a DOM tree, e.g. HTMLXHTMLXUL and SVG documents.

Historically, like DOM, the event models used by various web browsers had some significant differences. This caused compatibility problems. To combat this, the event model was standardized by the W3C in DOM Level 2.

Events[edit]

HTML events[edit]

Common/W3C events[edit]

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

  • Mouse events
  • Keyboard events
  • HTML frame/object events
  • HTML form events
  • User interface events
  • Mutation events (notification of any changes to the structure of a document)

Note that the event classification above is not exactly the same as W3C's classification.

Category Type Attribute Description Bubbles Cancelable
MouseclickonclickFires when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is:
  • mousedown
  • mouseup
  • click
YesYes
dblclickondblclickFires when the pointing device button is double clicked over an elementYesYes
mousedownonmousedownFires when the pointing device button is pressed over an elementYesYes
mouseuponmouseupFires when the pointing device button is released over an elementYesYes
mouseoveronmouseoverFires when the pointing device is moved onto an elementYesYes
mousemoveonmousemoveFires when the pointing device is moved while it is over an elementYesNo
mouseoutonmouseoutFires when the pointing device is moved away from an elementYesYes
KeyboardkeydownonkeydownFires before keypress, when a key on the keyboard is pressed.YesYes
keypressonkeypressFires after keydown, when a key on the keyboard is pressed.YesYes
keyuponkeyupFires when a key on the keyboard is releasedYesYes
HTML frame/objectloadonloadFires when the user agent finishes loading all content within a document, including window, frames, objects and images

For elements, it fires when the target element and all of its content has finished loading

NoNo
unloadonunloadFires when the user agent removes all content from a window or frame

For elements, it fires when the target element or any of its content has been removed

NoNo
abortonabortFires when an object/image is stopped from loading before completely loadedYesNo
erroronerrorFires when an object/image/frame cannot be loaded properlyYesNo
resizeonresizeFires when a document view is resizedYesNo
scrollonscrollFires when a document view is scrolledYesNo
HTML formselectonselectFires when a user selects some text in a text field, including input and textareaYesNo
changeonchangeFires when a control loses the input focus and its value has been modified since gaining focusYesNo
submitonsubmitFires when a form is submittedYesYes
resetonresetFires when a form is resetYesNo
focusonfocusFires when an element receives focus either via the pointing device or by tab navigationNoNo
bluronblurFires when an element loses focus either via the pointing device or by tabbing navigationNoNo
User interfacefocusin(none)Similar to HTML focus event, but can be applied to any focusable elementYesNo
focusout(none)Similar to HTML blur event, but can be applied to any focusable elementYesNo
DOMActivate(none)Similar to XUL command event. Fires when an element is activated, for instance, through a mouse click or a keypress.YesYes
MutationDOMSubtreeModified(none)Fires when the subtree is modifiedYesNo
DOMNodeInserted(none)Fires when a node has been added as a child of another nodeYesNo
DOMNodeRemoved(none)Fires when a node has been removed from a DOM-treeYesNo
DOMNodeRemovedFromDocument(none)Fires when a node is being removed from a documentNoNo
DOMNodeInsertedIntoDocument(none)Fires when a node is being inserted into a documentNoNo
DOMAttrModified(none)Fires when an attribute has been modifiedYesNo
DOMCharacterDataModified(none)Fires when the character data has been modifiedYesNo

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, with the exception of DOMAttrModified.

Touch events[edit]

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

Category Type Attribute Description Bubbles Cancelable
Touchtouchstart Fires when a finger is placed on the touch surface/screen.YesYes
touchend Fires when a finger is removed from the touch surface/screen.YesYes
touchmove Fires when a finger already placed on the screen is moved across the screen.YesYes
touchenter Fires when a touch point moves onto the interactive area defined by a DOM element.YesYes
touchleave Fires when a touch point moves off the interactive area defined by a DOM element.YesYes
touchcancel 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.[1]:§5.9YesNo

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

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

Microsoft-specific events[edit]

Two major types of events are added by Microsoft, and in some cases can only be used in Internet Explorer. Others have been implemented as de facto standards by other browsers.

Category Type Attribute Description Bubbles Cancelable
ClipboardcutoncutFires after a selection is cut to the clipboard.YesYes
copyoncopyFires after a selection is copied to the clipboard.YesYes
pasteonpasteFires after a selection is pasted from the clipboard.YesYes
beforecutonbeforecutFires before a selection is cut to the clipboard.YesYes
beforecopyonbeforecopyFires before a selection is copied to the clipboard.YesYes
beforepasteonbeforepasteFires before a selection is pasted from the clipboard.YesYes
Data bindingafterupdateonafterupdateFires immediately after a databound object has been updated.YesNo
beforeupdateonbeforeupdateFires before a data source is updated.YesYes
cellchangeoncellchangeFires when a data source has changed.YesNo
dataavailableondataavailableFires when new data from a data source become available.YesNo
datasetchangedondatasetchangedFires when content at a data source has changed.YesNo
datasetcompleteondatasetcompleteFires when transfer of data from the data source has completed.YesNo
errorupdateonerrorupdateFires if an error occurs while updating a data field.YesNo
rowenteronrowenterFires when a new row of data from the data source is available.YesNo
rowexitonrowexitFires when a row of data from the data source has just finished.NoYes
rowsdeleteonrowsdeleteFires when a row of data from the data source is deleted.YesNo
rowinsertedonrowinsertedFires when a row of data from the data source is inserted.YesNo
MousecontextmenuoncontextmenuFires when the context menu is shown.YesYes
dragondragFires when during a mouse drag (on the moving Element).YesYes
dragstartondragstartFires when a mouse drag begins (on the moving Element).YesYes
dragenterondragenterFires when something is dragged onto an area (on the target Element).YesYes
dragoverondragoverFires when a drag is held over an area (on the target Element).YesYes
dragleaveondragleaveFires when something is dragged out of an area (on the target Element).YesYes
dragendondragendFires when a mouse drag ends (on the moving Element).YesYes
dropondropFires when a mouse button is released over a valid target during a drag (on the target Element).YesYes
selectstartonselectstartFires when the user starts to select text.YesYes
KeyboardhelponhelpFires when the user initiates help.YesYes
HTML frame/objectbeforeunloadonbeforeunloadFires before a document is unloaded.NoYes
stoponstopFires when the user stops loading the object. (unlike abort, stop event can be attached to document)NoNo
HTML formbeforeeditfocusonbeforeeditfocusFires before an element gains focus for editing.YesYes
MarqueestartonstartFires when a marquee begins a new loop.NoNo
finishonfinishFires when marquee looping is complete.NoYes
bounceonbounceFires when a scrolling marquee bounces back in the other direction.NoYes
MiscellaneousbeforeprintonbeforeprintFires before a document is printedNoNo
afterprintonafterprintFires immediately after the document prints.NoNo
propertychangeonpropertychangeFires when the property of an object is changed.NoNo
filterchangeonfilterchangeFires when a filter changes properties or finishes a transition.NoNo
readystatechangeonreadystatechangeFires when the readyState property of an element changes.NoNo
losecaptureonlosecaptureFires when the releaseCapture method is invoked.NoNo

Note that Mozilla, Safari and Opera also support readystatechange event for the XMLHttpRequest object. Mozilla also supports the beforeunload event using traditional event registration method (DOM Level 0). Mozilla and Safari also support contextmenu, but Internet Explorer for the Mac does not.

Note that Firefox 6 and later support 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.

Category Type Attribute Description Bubbles Cancelable
MouseDOMMouseScrollDOMMouseScrollFires when the mouse wheel is moved, causing the content to scroll.YesYes
dragdropondragdropFires when the user releases the mouse button to drop an object being dragged.NoNo
dragenterondragenterFires when the mouse pointer first moves over an element during a drag. It is similar to the mouseover event but occurs while dragging.NoNo
dragexitondragexitFires when the mouse pointer moves away from an element during a drag. It is also called after a drop on an element. It is similar to the mouseout event but occurs during a drag.NoNo
draggestureondraggestureFires when the user starts dragging the element, usually by holding down the mouse button and moving the mouse.NoNo
dragoverondragoverRelated to the mousemove event, this event is fired while something is being dragged over an element.NoNo
InputCheckboxStateChange Fires when a checkbox is checked or unchecked, either by the user or a script.NoNo
RadioStateChange Fires when a radio button is selected, either by the user or a script.NoNo
closeoncloseFires when a request has been made to close the window.NoYes
commandoncommandSimilar to W3C DOMActivate event. Fires when an element is activated, for instance, through a mouse click or a keypress.NoNo
inputoninputFires when a user enters text in a textbox.YesNo
User interfaceDOMMenuItemActiveDOMMenuItemActiveFires when a menu or menuitem is hovered over, or highlighted.YesNo
DOMMenuItemInactiveDOMMenuItemInactiveFires when a menu or menuitem is no longer being hovered over, or highlighted.YesNo
contextmenuoncontextmenuFires when the user requests to open the context menu for the element. The action to do this varies by platform, but it will typically be a right click.NoYes
overflowonoverflowFires a box or other layout element when there is not enough space to display it at full size.NoNo
overflowchangedonoverflowchangedFires when the overflow state changes.NoNo
underflowonunderflowFires to an element when there becomes enough space to display it at full size.NoNo
popuphiddenonpopuphiddenFires to a popup after it has been hidden.NoNo
popuphidingonpopuphidingFires to a popup when it is about to be hidden.NoNo
popupshowingonpopupshowingFires to a popup just before it is popped open.NoYes
popupshownonpopupshownFires to a popup after it has been opened, much like the onload event is sent to a window when it is opened.NoNo
CommandbroadcastonbroadcastPlaced on an observer. The broadcast event is sent when the attributes of the broadcaster being listened to are changed.NoNo
commandupdateoncommandupdateFires when a command update occurs.NoNo

Other events[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 Draft Specification. The "DOMContentLoaded" event was also implemented in the Webkit rendering engine build 500+.[3] This correlates to all versions of Google Chrome and Safari 3.1+. DOMContentLoaded is also implemented in Internet Explorer 9.[4]

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

Event flow[edit]

Consider the situation when there are 2 elements nested together. Both have event handlers registered on the same event type, say "click". When the user clicks on the inner element, there are two possible ways to handle it:

  • Trigger the elements from outer to inner (event capturing). This model is implemented in Netscape Navigator.
  • Trigger the elements from inner to outer (event bubbling). This model is implemented in Internet Explorer and other browsers.[5]

W3C takes a middle position in this struggle.[6]:§1.2 Events are first captured until it reaches the target element, and then bubbled up. During the event flow, an event can be responded to at any element in the path (an observer) in either phase by causing an action, and/or by stopping the event (with method event.stopPropagation() for W3C-conforming browsers and command event.cancelBubble = true for Internet Explorer), and/or by cancelling the default action for the event.

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
Type Name Description
DOMStringtypeThe name of the event (case-insensitive in DOM level 2 but case-sensitive in DOM level 3 [7]).
EventTargettargetUsed to indicate the EventTarget to which the event was originally dispatched.
EventTargetcurrentTargetUsed to indicate the EventTarget whose EventListeners are currently being processed.
unsigned shorteventPhaseUsed to indicate which phase of event flow is currently being evaluated.
booleanbubblesUsed to indicate whether or not an event is a bubbling event.
booleancancelableUsed to indicate whether or not an event can have its default action prevented.
DOMTimeStamptimeStampUsed to specify the time (in milliseconds relative to the epoch) at which the event was created.
Event methods
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.
initEventDOMStringeventTypeArgSpecifies the event type.
booleancanBubbleArgSpecifies whether or not the event can bubble.
booleancancelableArgSpecifies whether or not the event's default action can be prevented.

Event handling models[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: inline model and traditional model.

Inline model[edit]

In the inline model,[8] event handlers are added as attributes of elements. In the example below, an alert dialog box with the message "Hey Joe" appears after thehyperlink 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 thetriggerAlert 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 ananonymous 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,[9] event handlers can be added/removed by scripts. Like the inline model, each event can only have one event handler registered. The event is added by assigning the handler name to the event property of the element object. To remove an event handler, simply set the property to null:

<!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.[6]

Name Description Argument type Argument name
addEventListenerAllows the registration of event listeners on the event target.DOMStringtype
EventListenerlistener
booleanuseCapture
removeEventListenerAllows the removal of event listeners from the event target.DOMStringtype
EventListenerlistener
booleanuseCapture
dispatchEventAllows to send the event to the subscribed event listeners.Eventevt

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

Microsoft-specific model[edit]

Microsoft does not follow the W3C model up until Internet Explorer 8, as its own model was created prior to the ratification of the W3C standard. Internet Explorer 9 is supposed to follow DOM level 3 events.[10]

Name Description Argument type Argument name
attachEventSimilar to W3C's addEventListener method.StringsEvent
PointerfpNotify
detachEventSimilar to W3C's removeEventListener method.StringsEvent
PointerfpNotify
fireEventSimilar to W3C's dispatchEvent method.StringsEvent
EventoEventObject

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. MaxthonAvant Browser).

A rewrite of the example used in the traditional model[edit]
<!doctype html>
<html lang="en">
<head>
     <meta charset="utf-8">
     <title>Microsoft-specific model</title>
</head>
<body>
     <h1>Microsoft-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]

External links[edit]

References[edit]

  1. a b c "Touch Events version 2 - W3C Editor's Draft". W3C. 14 November 2011. Retrieved 10 December 2011.
  2. ^ "Apple using patents to undermine open standards again". opera.com. 9 December 2011. Retrieved 9 December 2011.
  3. ^ [1][dead link]
  4. ^ http://ie.microsoft.com/testdrive/HTML5/87DOMContent-Loaded/Default.html
  5. ^ "Introduction to Events". Quirksmode.org. Retrieved 15 September 2012.
  6. a b "Document Object Model (DOM) Level 2 Events Specification"W3C. 13 November 2000. Retrieved 15 September 2012.
  7. ^ "Document Object Model (DOM) Level 3 Events Specification (working draft)"W3C. Retrieved 2013-04-17.
  8. ^ "Early event handlers". Quirksmode.org. Retrieved 15 September 2012.
  9. ^ "Traditional event registration model". Quirksmode.org. Retrieved 15 September 2012.
  10. ^ "DOM Level 3 Events support in IE9"Microsoft. March 26, 2010. Retrieved 2010-03-28.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值