Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

DOM event

From Wikipedia, the free encyclopedia
Signal for Document Object Model
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This articlecontainsinstructions, advice, or how-to content. Please helprewrite the content so that it is more encyclopedic ormove it toWikiversity,Wikibooks, orWikivoyage.(July 2018)
This articlemay be too technical for most readers to understand. Pleasehelp improve it tomake it understandable to non-experts, without removing the technical details.(July 2018) (Learn how and when to remove this message)
(Learn how and when to remove this message)

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 likeJavaScript,JScript,VBScript, andJava can register variousevent handlers orlisteners on the element nodes inside aDOM tree, such as inHTML,XHTML,XUL, andSVG 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 variousweb browsers had some significant differences which caused compatibility problems. To combat this, the event model was standardized by theWorld 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 byXMLHttpRequest and File API[6]).

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

CategoryTypeAttributeDescriptionBubblesCancelable
MouseclickonclickFires when thepointing 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 isdouble-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
mousemove[7]onmousemoveFires when the pointing device is moved while it is over an elementYesYes
mouseoutonmouseoutFires when the pointing device is moved away from an elementYesYes
dragstartondragstartFired on an element when a drag is started.YesYes
dragondragThis event is fired at the source of the drag, that is, the element where dragstart was fired, during the drag operation.YesYes
dragenterondragenterFired when the mouse is first moved over an element while a drag is occurring.YesYes
dragleaveondragleaveThis event is fired when the mouse leaves an element while a drag is occurring.YesNo
dragoverondragoverThis event is fired as the mouse is moved over an element when a drag is occurring.YesYes
dropondropThe drop event is fired on the element where the drop occurs at the end of the drag operation.YesYes
dragendondragendThe source of the drag will receive a dragend event when the drag operation is complete, whether it was successful or not.YesNo
KeyboardkeydownonkeydownFires before keypress, when a key on the keyboard is pressed.YesYes
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 theuser 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 an element or document view is scrolledNo, except that a scroll event on document must bubble to the window[8]No
HTML formselectonselectFires when a user selects some text in atext field, including input and textareaYesNo
changeonchangeFires when a control loses the inputfocus 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 bytab navigationNoNo
bluronblurFires when an element loses focus either via the pointing device or bytabbing 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
Progressloadstart(none)Progress has begun.NoNo
progress(none)In progress. After loadstart has been dispatched.NoNo
error(none)Progression failed. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.NoNo
abort(none)Progression is terminated. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.NoNo
load(none)Progression is successful. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.NoNo
loadend(none)Progress has stopped. After one of error, abort, or load has been dispatched.NoNo

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

Touch events

[edit]

Web browsers running ontouch-enabled devices, such as Apple'siOS and Google'sAndroid, generate additional events.[9]: §5.3 

CategoryTypeAttributeDescriptionBubblesCancelable
TouchtouchstartFires when a finger is placed on the touch surface/screen.YesYes
touchendFires when a finger is removed from the touch surface/screen.YesYes
touchmoveFires when a finger already placed on the screen is moved across the screen.YesYes
touchenterFires when a touch point moves onto the interactive area defined by a DOM element.YesYes
touchleaveFires when a touch point moves off the interactive area defined by a DOM element.YesYes
touchcancelAuser 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 YesNo

In theW3C draft recommendation, aTouchEvent delivers aTouchList ofTouch locations, themodifier keys that were active, aTouchList ofTouch locations within the targeted DOM element, and aTouchList ofTouch locations that have changed since the previousTouchEvent.[9]

Apple didn't join this working group, and delayed W3C recommendation of its Touch Events Specification by disclosingpatents 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]

CategoryTypeAttributeDescriptionBubblesCancelable
PointerpointerdownonpointerdownFires when the pointing device button is activated, or pressed over an element.YesYes
pointeruponpointerupFires when the pointing device button is released over an elementYesYes
pointercancelonpointercancelFires when a pointing device is unlikely to continue to produce event because, for example, the device is used for panning/zooming after a pointerdown event.YesYes
pointermoveonpointermoveFires when the pointing device is moved while it is over an elementYesYes
pointeroveronpointeroverFires when the pointing device is moved onto an elementYesYes
pointeroutonpointeroutFires when the pointing device is moved away from an element. Also fires after pointerup by pointing device without hovering, or afterYesYes
pointerenteronpointerenterFires when the pointing device is moved onto an element, or when the button of the pointing device which does not support hovering is pressed on one of its descendant elements.NoYes
pointerleaveonpointerleaveFires when the pointing device is moved away from an element, or when the button of the pointing device which does not support hovering is released over its descendant elements.NoYes
gotpointercaptureongotpointercaptureFires when the pointer is captured by setPointerCapture method.YesNo
lostpointercaptureonlostpointercaptureFires when the pointer is released by releasePointerCapture method.YesNo

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.

CategoryTypeDescriptionBubblesCancelable
RequestundorequestIndicates the user desires to "undo" the previous action. (May be superseded by the UndoManager interface.)YesYes
redorequestIndicates the user desires to "redo" the previously "undone" action. (May be superseded by the UndoManager interface.)YesNo
expandrequestIndicates the user desires to reveal information in a collapsed section (e.g. a disclosure widget) or branch node in a hierarchy (e.g., atree view).YesYes
collapserequestIndicates 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).YesYes
dismissrequestIndicates the user desires "dismiss" the current view (e.g. canceling a dialog, or closing a popup menu).YesYes
deleterequestIndicates the user wants to initiate a "delete" action on the marked element or current view.YesYes
Focus RequestdirectionalfocusrequestInitiated when the user agent sends a "direction focus" request to the web application. Web authors should not use or register for directionalfocusrequest events when standard browser focus and blur events are sufficient. Using these events unnecessarily could result in reduced performance or negative user experience.YesYes
linearfocusrequestInitiated when the user agent sends a "linear focus" request to the web application. Web authors should not use or register for linearfocusrequest events when standard browser focus and blur events are sufficient. This event type is only necessary on specialized control types such as data grids where the logical next element may not be focusable or even in the DOM until requested. Using these events unnecessarily could result in reduced performance or negative user experience.YesYes
palettefocusrequestInitiated when the user agent sends a "palette focus" request to the web application. Web app authors receiving this event should move focus to the first palette in the web application, or cycle focus between all available palettes. Note: palettes are sometimes referred to as non-modal dialogs or inspector windows.YesYes
toolbarfocusrequestInitiated when the user agent sends a "toolbar focus" request to the web application. Web app authors receiving this event should move focus to the main toolbar in the web application, or cycle focus between all available toolbars.YesYes
Manipulation RequestmoverequestInitiated when the user agent sends a move request to the web application with accompanying x/y delta values. This is used, for example, when moving an object to a new location on a layout canvas.YesYes
panrequestInitiated when the user agent sends a pan request to the web application with accompanying x/y delta values. This is used, for example, when changing the center point while panning a map or another custom image viewer.YesYes
rotationrequestInitiated when the user agent sends a rotation request to the web application with accompanying origin x/y values and a rotation value in degrees.YesYes
zoomrequestInitiated when the user agent sends a zoom request to the web application with accompanying origin x/y values and the zoom scale factor.YesYes
Scroll RequestscrollrequestInitiated when the user agent sends a scroll request to the web application with accompanying x/y delta values or one of the other defined scrollType values. Authors should only use this event and uiaction with custom scroll views.YesYes
ValueChange RequestvaluechangerequestInitiated when the user agent sends a value change request to the web application. Used on custom range controls like sliders, carousels, etc.YesYes

Internet Explorer-specific events

[edit]

In addition to the common (W3C) events, two major types of events are added byInternet Explorer. Some of the events have been implemented asde facto standards by other browsers.

CategoryTypeAttributeDescriptionBubblesCancelable
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 amouse 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 the readystatechange event for theXMLHttpRequest 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 withXUL elements.[citation needed]

CategoryTypeAttributeDescriptionBubblesCancelable
MouseDOMMouseScrollDOMMouseScrollFires when the mouse wheel is moved, causing the content to scroll.YesYes
dragdropondragdropFires when the user releases the mouse button todrop 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
InputCheckboxStateChangeFires when a checkbox is checked or unchecked, either by the user or a script.NoNo
RadioStateChangeFires 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 ishovered 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 asDOMContentLoaded andDOMFrameContentLoaded 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 theHTML 5 specification.[13]The DOMContentLoaded event was also implemented in theWebkit rendering engine build 500+.[14][15] This correlates to all versions ofGoogle Chrome andSafari 3.1+. DOMContentLoaded is also implemented inInternet Explorer 9.[16]

Opera 9 also supports the Web Forms 2.0 eventsDOMControlValueChanged,invalid,forminput andformchange.

Event flow

[edit]

Consider the situation when two event targets participate in atree. 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 inNetscape 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 (whereevent.bubbles == true)

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

Stopping events

[edit]

While an event is travelling through event listeners, the event can be stopped withevent.stopPropagation() orevent.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 theevent.cancelBubble totrue (Internet Explorer)
  • Set theevent.returnValue property tofalse

Canceling events

[edit]

Acancelable event can be canceled by callingevent.preventDefault(). Canceling an event will opt out of the default browser behaviour for that event. When an event is canceled, theevent.defaultPrevented property will be set totrue. 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
NameTypeDescription
typeDOMStringThe name of the event (case-insensitive in DOM level 2 but case-sensitive in DOM level 3[19]).
targetEventTargetUsed to indicate the EventTarget to which the event was originally dispatched.
currentTargetEventTargetUsed to indicate the EventTarget whose EventListeners are currently being processed.
eventPhaseunsigned shortUsed to indicate which phase of event flow is currently being evaluated.
bubblesbooleanUsed to indicate whether or not an event is a bubbling event.
cancelablebooleanUsed to indicate whether or not an event can have its default action prevented.
timeStampDOMTimeStampUsed to specify the time (in milliseconds relative to the epoch) at which the event was created.
Event methods
NameArgument typeArgument nameDescription
stopPropagationTo prevent further propagation of an event during event flow.
preventDefaultTo cancel the event if it is cancelable, meaning that any default action normally taken by the implementation as a result of the event will not occur.
initEventDOMStringeventTypeArgSpecifies the event type.
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 byNetscape Navigator, and remains the most cross-browser model as of 2005[update].[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, analert 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><htmllang="en"><head><metacharset="utf-8"><title>Inline Event Handling</title></head><body><h1>Inline Event Handling</h1><p>Hey<ahref="http://www.example.com"onclick="triggerAlert('Joe'); return false;">Joe</a>!</p><script>functiontriggerAlert(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 theJavaScript engine of the browser creates ananonymous function containing the statements in theonclick attribute. Theonclick handler of the element would be bound to the following anonymous function:

function(){triggerAlert('Joe');returnfalse;}

This limitation of the JavaScript event model is usually overcome by assigning attributes to the function object of the event handler or by usingclosures.

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><htmllang="en"><head><metacharset="utf-8"><title>Traditional Event Handling</title></head><body><h1>Traditional Event Handling</h1><p>Hey Joe!</p><script>vartriggerAlert=function(){window.alert("Hey Joe");};// Assign an event handlerdocument.onclick=triggerAlert;// Assign another event handlerwindow.onload=triggerAlert;// Remove the event handler that was just assignedwindow.onload=null;</script></body></html>

To add parameters:

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

Inner functions preserve theirscope.

DOM Level 2

[edit]

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

NameDescriptionArgument typeArgument 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 sending the event to the subscribed event listeners.Eventevt

Some useful things to know :

  • To prevent an event from bubbling, developers must call thestopPropagation() method of the event object.
  • To prevent the default action of the event to be called, developers must call thepreventDefault() method of the event object.

The main difference from the traditional model is that multiple event handlers can be registered for the same event. TheuseCapture 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 byMozilla,Opera,Safari,Chrome andKonqueror.

A rewrite of the example used in the traditional model

[edit]
<!doctype html><htmllang="en"><head><metacharset="utf-8"><title>DOM Level 2</title></head><body><h1>DOM Level 2</h1><p>Hey Joe!</p><script>varheyJoe=function(){window.alert("Hey Joe!");}// Add an event handlerdocument.addEventListener("click",heyJoe,true);// capture phase// Add another event handlerwindow.addEventListener("load",heyJoe,false);// bubbling phase// Remove the event handler just addedwindow.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]

NameDescriptionArgument typeArgument 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'scancelBubble property.
  • To prevent the default action of the event to be called, developers must set the event'sreturnValue property.
  • Thethis keyword refers to the globalwindow object.

Again, this model differs from the traditional model in that multiple event handlers can be registered for the same event. However theuseCapture option can not be used to specify that the handler should be called in the capture phase. This model is supported by MicrosoftInternet Explorer andTrident based browsers (e.g.Maxthon, Avant Browser).

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

[edit]
<!doctype html><htmllang="en"><head><metacharset="utf-8"><title>Internet Explorer-specific model</title></head><body><h1>Internet Explorer-specific model</h1><p>Hey Joe!</p><script>varheyJoe=function(){window.alert("Hey Joe!");}// Add an event handlerdocument.attachEvent("onclick",heyJoe);// Add another event handlerwindow.attachEvent("onload",heyJoe);// Remove the event handler just addedwindow.detachEvent("onload",heyJoe);</script></body></html>

References

[edit]
  1. ^"DOM Standard".dom.spec.whatwg.org. Retrieved2021-05-25.
  2. ^"JavaScript DOM Events".www.w3schools.com. Retrieved2019-08-03.
  3. ^"7.8 Drag and drop — HTML5".
  4. ^"HTML Drag and Drop API". 28 March 2024.
  5. ^"Progress Events".
  6. ^"File API".
  7. ^"Element: Mousemove event - Web APIs | MDN". 22 December 2023.
  8. ^"Document Object Model (DOM) Level 3 Events Specification (working draft)".W3C. Retrieved2013-04-17.
  9. ^abc"Touch Events version 2 - W3C Editor's Draft". W3C. 14 November 2011. Retrieved10 December 2011.
  10. ^"Apple using patents to undermine open standards again". opera.com. 9 December 2011. Retrieved9 December 2011.
  11. ^"Pointer Events".
  12. ^"IndieUI: Events 1.0".
  13. ^"HTML Standard".
  14. ^[1]Archived June 11, 2010, at theWayback Machine
  15. ^"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)
  16. ^"Test Drive Redirect". Archived fromthe original on 2010-05-08. Retrieved2010-05-06.
  17. ^"Introduction to Events". Quirksmode.org. Retrieved15 September 2012.
  18. ^ab"Document Object Model (DOM) Level 2 Events Specification".W3C. 13 November 2000. Retrieved15 September 2012.
  19. ^"Document Object Model (DOM) Level 3 Events Specification (working draft)".W3C. Retrieved2013-04-17.
  20. ^"Early event handlers". Quirksmode.org. Retrieved15 September 2012.
  21. ^"Traditional event registration model". Quirksmode.org. Retrieved15 September 2012.
  22. ^"DOM Level 3 Events support in IE9".Microsoft. March 26, 2010. Retrieved2010-03-28.
  23. ^"Compatibility changes in IE11 Preview".Microsoft. September 9, 2013. Retrieved2013-10-05.

Further reading

[edit]

External links

[edit]
Protocols
Server APIs
Apache modules
Topics
Browser APIs
Web APIs
WHATWG
W3C
Khronos
Others
Topics
Related topics
Retrieved from "https://en.wikipedia.org/w/index.php?title=DOM_event&oldid=1267067316"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp