DOM Events
Encyclopedia
DOM events allow event-driven programming
Event-driven programming
In computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events—i.e., sensor outputs or user actions or messages from other programs or threads.Event-driven programming can also be defined as an...

 languages like JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

, JScript
JScript
JScript is a scripting language based on the ECMAScript standard that is used in Microsoft's Internet Explorer.JScript is implemented as a Windows Script engine. This means that it can be "plugged in" to any application that supports Windows Script, such as Internet Explorer, Active Server Pages,...

, ECMAScript
ECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...

, VBScript
VBScript
VBScript is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. It is designed as a “lightweight” language with a fast interpreter for use in a wide variety of Microsoft environments...

 and Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 to register various event handlers/listeners on the element nodes inside a DOM
Document Object Model
The Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...

 tree, e.g. HTML
HTML
HyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....

, XHTML
XHTML
XHTML is a family of XML markup languages that mirror or extend versions of the widely-used Hypertext Markup Language , the language in which web pages are written....

, XUL
XUL
In computer programming, XUL , the XML User Interface Language, is an XML user interface markup language developed by the Mozilla project. XUL operates in Mozilla cross-platform applications such as Firefox...

 and SVG
Scalable Vector Graphics
Scalable Vector Graphics is a family of specifications of an XML-based file format for describing two-dimensional vector graphics, both static and dynamic . The SVG specification is an open standard that has been under development by the World Wide Web Consortium since 1999.SVG images and their...

 documents.

Historically, like DOM, the event models used by various web browser
Web browser
A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...

s had some significant differences. This caused compatibility problems. To combat this, the event model was standardized by the W3C
World Wide Web Consortium
The World Wide Web Consortium is the main international standards organization for the World Wide Web .Founded and headed by Tim Berners-Lee, the consortium is made up of member organizations which maintain full-time staff for the purpose of working together in the development of standards for the...

 in DOM Level 2.

Common/W3C events

There is a huge collection of events that can be generated by most element nodes:
  • Mouse events
  • Keyboard
    Computer keyboard
    In computing, a keyboard is a typewriter-style keyboard, which uses an arrangement of buttons or keys, to act as mechanical levers or electronic switches...

     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
Mouse click onclick Fires when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is:
  • mousedown
  • mouseup
  • click
Yes Yes
dblclick ondblclick Fires when the pointing device button is double clicked over an element Yes Yes
mousedown onmousedown Fires when the pointing device button is pressed over an element Yes Yes
mouseup onmouseup Fires when the pointing device button is released over an element Yes Yes
mouseover onmouseover Fires when the pointing device is moved onto an element Yes Yes
mousemove onmousemove Fires when the pointing device is moved while it is over an element Yes No
mouseout onmouseout Fires when the pointing device is moved away from an element Yes Yes
Keyboard keydown onkeydown Fires before keypress, when a key on the keyboard is pressed. Yes Yes
keypress onkeypress Fires after keydown, when a key on the keyboard is pressed. Yes Yes
keyup onkeyup Fires when a key on the keyboard is released Yes Yes
HTML frame/object load onload Fires when the user agent
User agent
In computing, a user agent is a client application implementing a network protocol used in communications within a client–server distributed computing system...

 finishes loading all content within a document, including window, frames, objects and images
For elements, it fires when the target element and all of its content has finished loading
No No
unload onunload Fires when the user agent removes all content from a window or frame
For elements, it fires when the target element or any of its content has been removed
No No
abort onabort Fires when an object/image is stopped from loading before completely loaded Yes No
error onerror Fires when an object/image/frame cannot be loaded properly Yes No
resize onresize Fires when a document view is resized Yes No
scroll onscroll Fires when a document view is scrolled Yes No
HTML form select onselect Fires when a user selects some text in a text field, including input and textarea Yes No
change onchange Fires when a control loses the input focus and its value has been modified since gaining focus Yes No
submit onsubmit Fires when a form is submitted Yes Yes
reset onreset Fires when a form is reset Yes No
focus onfocus Fires when an element receives focus either via the pointing device or by tab navigation No No
blur onblur Fires when an element loses focus either via the pointing device or by tabbing navigation No No
User interface DOMFocusIn (none) Similar to HTML focus event, but can be applied to any focusable element Yes No
DOMFocusOut (none) Similar to HTML blur event, but can be applied to any focusable element Yes No
DOMActivate (none) Similar to XUL command event. Fires when an element is activated, for instance, through a mouse click or a keypress. Yes Yes
Mutation DOMSubtreeModified (none) Fires when the subtree is modified Yes No
DOMNodeInserted (none) Fires when a node has been added as a child of another node Yes No
DOMNodeRemoved (none) Fires when a node has been removed from a DOM-tree Yes No
DOMNodeRemovedFromDocument (none) Fires when a node is being removed from a document No No
DOMNodeInsertedIntoDocument (none) Fires when a node is being inserted into a document No No
DOMAttrModified (none) Fires when an attribute has been modified Yes No
DOMCharacterDataModified (none) Fires when the character data has been modified Yes No


Note that the events whose names start with “DOM” are currently not well supported. Mozilla
Mozilla
Mozilla is a term used in a number of ways in relation to the Mozilla.org project and the Mozilla Foundation, their defunct commercial predecessor Netscape Communications Corporation, and their related application software....

 and Opera
Opera (web browser)
Opera is a web browser and Internet suite developed by Opera Software with over 200 million users worldwide. The browser handles common Internet-related tasks such as displaying web sites, sending and receiving e-mail messages, managing contacts, chatting on IRC, downloading files via BitTorrent,...

 support DOMAttrModified, DOMNodeInserted, DOMNodeRemoved and DOMCharacterDataModified. Chrome
Google Chrome
Google Chrome is a web browser developed by Google that uses the WebKit layout engine. It was first released as a beta version for Microsoft Windows on September 2, 2008, and the public stable release was on December 11, 2008. The name is derived from the graphical user interface frame, or...

 and Safari
Safari (web browser)
Safari is a web browser developed by Apple Inc. and included with the Mac OS X and iOS operating systems. First released as a public beta on January 7, 2003 on the company's Mac OS X operating system, it became Apple's default browser beginning with Mac OS X v10.3 "Panther". Safari is also the...

 also support these events, with the exception of DOMAttrModified.

Microsoft-specific events

Two major types of events are added by Microsoft, and in some cases can only be used in Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...

. Others have been implemented as de-facto standards by other browsers.
  • Clipboard
    Clipboard
    A clipboard is a thin, rigid 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 available.-Other uses:...

     events
  • Data binding events

Category Type Attribute Description Bubbles Cancelable
Clipboard cut oncut Fires after a selection is cut to the clipboard. Yes Yes
copy oncopy Fires after a selection is copied to the clipboard. Yes Yes
paste onpaste Fires after a selection is pasted from the clipboard. Yes Yes
beforecut onbeforecut Fires before a selection is cut to the clipboard. Yes Yes
beforecopy onbeforecopy Fires before a selection is copied to the clipboard. Yes Yes
beforepaste onbeforepaste Fires before a selection is pasted from the clipboard. Yes Yes
Data binding afterupdate onafterupdate Fires immediately after a databound object has been updated. Yes No
beforeupdate onbeforeupdate Fires before a data source is updated. Yes Yes
cellchange oncellchange Fires when a data source has changed. Yes No
dataavailable ondataavailable Fires when new data from a data source become available. Yes No
datasetchanged ondatasetchanged Fires when content at a data source has changed. Yes No
datasetcomplete ondatasetcomplete Fires when transfer of data from the data source has completed. Yes No
errorupdate onerrorupdate Fires if an error occurs while updating a data field. Yes No
rowenter onrowenter Fires when a new row of data from the data source is available. Yes No
rowexit onrowexit Fires when a row of data from the data source has just finished. No Yes
rowsdelete onrowsdelete Fires when a row of data from the data source is deleted. Yes No
rowinserted onrowinserted Fires when a row of data from the data source is inserted. Yes No
Mouse contextmenu oncontextmenu Fires when the context menu is shown. Yes Yes
drag ondrag Fires when during a mouse drag (on the moving Element). Yes Yes
dragstart ondragstart Fires when a mouse drag begins (on the moving Element). Yes Yes
dragenter ondragenter Fires when something is dragged onto an area (on the target Element). Yes Yes
dragover ondragover Fires when a drag is held over an area (on the target Element). Yes Yes
dragleave ondragleave Fires when something is dragged out of an area (on the target Element). Yes Yes
dragend ondragend Fires when a mouse drag ends (on the moving Element). Yes Yes
drop ondrop Fires when a mouse button is released over a valid target during a drag (on the target Element). Yes Yes
selectstart onselectstart Fires when the user starts to select text. Yes Yes
Keyboard help onhelp Fires when the user initiates help. Yes Yes
HTML frame/object beforeunload onbeforeunload Fires before a document is unloaded. No Yes
stop onstop Fires when the user stops loading the object. (unlike abort, stop event can be attached to document) No No
HTML form beforeeditfocus onbeforeeditfocus Fires before an element gains focus for editing. Yes Yes
Marquee start onstart Fires when a marquee begins a new loop. No No
finish onfinish Fires when marquee looping is complete. No Yes
bounce onbounce Fires when a scrolling marquee bounces back in the other direction. No Yes
Miscellaneous beforeprint onbeforeprint Fires before a document is printed No No
afterprint onafterprint Fires immediately after the document prints. No No
propertychange onpropertychange Fires when the property of an object is changed. No No
filterchange onfilterchange Fires when a filter changes properties or finishes a transition. No No
readystatechange onreadystatechange Fires when the readyState property of an element changes. No No
losecapture onlosecapture Fires when the releaseCapture method is invoked. No No


Note that Mozilla, Safari and Opera also support readystatechange event for the XMLHttpRequest
XMLHttpRequest
XMLHttpRequest is an API available in web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script. The data might be received from the server as XML text or as plain text...

 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.

Touch events

Web browsers running on modern, touch-enabled devices have events, such as "touchstart", "touchend", "touchenter", "touchleave", "touchmove", and "touchcancel". Apple's iOS and Google's Android are two examples of mobile operating systems with support for these events in their web browsers.

When you put a finger down on the screen of the touch enabled devices, it kicks off the lifecycle of touch events and the following events get triggered.
  • touchstart: When a finger is placed on the touch surface/screen.
  • touchend: When a finger is removed from the touch surface/screen.
  • touchmove: When a finger already placed on the screen is moved across the screen.
  • touchenter: When a touch point moves onto the interactive area defined by a DOM element.
  • touchleave: When a touch point moves off the interactive area defined by a DOM element.
  • touchcancel: A user agent
    User agent
    In computing, a user agent is a client application implementing a network protocol used in communications within a client–server distributed computing system...

     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.


The TouchEvent, TouchPoint and TouchList interfaces are defined by w3.org in the Touch Events Specification
  • Interface TouchPoint

This interface defines an individual point of contact for a touch event.
interface TouchPoint {
readonly attribute long identifier;
readonly attribute EventTarget target;
readonly attribute DOMTimeStamp timestamp;
readonly attribute long screenX;
readonly attribute long screenY;
readonly attribute long clientX;
readonly attribute long clientY;
readonly attribute long pageX;
readonly attribute long pageY;
readonly attribute long radiusX;
readonly attribute long radiusY;
readonly attribute float rotationAngle;
readonly attribute float force;
readonly attribute boolean altKey;
readonly attribute boolean metaKey;
readonly attribute boolean ctrlKey;
readonly attribute boolean shiftKey;
};
Attributes
  1. altKey: true if the alt (Alternate) key modifier is activated; otherwise false.
  2. clientX: x-coordinate of point relative to the viewport, excluding any scroll offset.
  3. clientY: y-coordinate of point relative to the viewport, excluding any scroll offset.
  4. ctrlKey: true if the ctrl (Control) key modifier is activated; otherwise false.
  5. force: a relative value of pressure applied, in the range 0 to 1, where 0 is no pressure, and 1 is the highest level of pressure the touch device is capable of sensing; 0 if no value is known. This attribute may not be available on all user agents or platforms. In environments where force is available, the absolute pressure represented by the force attribute, and the sensitivity in levels of pressure, may vary.
  6. identifier: An identification number for each touch point, unique to that touch point per session.
  7. metaKey: true if the meta (Meta) key modifier is activated; otherwise false. On some platforms this attribute may map to a differently-named key modifier.
  8. pageX: x-coordinate of point relative to the viewport, including any scroll offset.
  9. pageY: y-coordinate of point relative to the viewport, including any scroll offset.
  10. radiusX: The radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the x-axis, in pixels of the same scale as screenX; 1 if no value is known. This attribute may not be available on all user agents or platforms.
  11. radiusY: The radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the y-axis, in pixels of the same scale as screenY; 1 if no value is known. This attribute may not be available on all user agents or platforms.
  12. rotationAngle: The angle (in degrees) that the ellipse described by radiusX and radiusY is rotated clockwise about its center; 0 if no value is known. The value must be in the range [0, 90). If the ellipse described by radiusX and radiusY is circular, then rotationAngle must be 0.
  13. screenX: x-coordinate of point relative to the screen.
  14. screenY: y-coordinate of point relative to the screen.
  15. shiftKey: true if the shift (Shift) key modifier is activated; otherwise false.
  16. target: the original proximal event target for this touch point. The target must be an Element.
  17. timestamp: The timestamp attribute represents the time when the TouchPoint was initiated and is represented as a DOMTimeStamp.
    • Interface TouchList

This interface defines a list of individual points of contact for a touch event.
interface TouchList {
readonly attribute unsigned long length;
caller getter TouchPoint item (in unsigned long index);
caller getter object identifiedPoint (in long identifier);
};

Attributes
  1. length: returns the number of touchpoints in the list.

Methods
  1. identifiedPoint : returns the first touchpoint with long identifier from the list. The value for the identifier should not be nullable and it is not an optional parameter.
  2. item : returns the touchpoint with index from the list,which is sorted in order from latest to earliest.The value for the index should not be nullable and it is an not optional parameter.
    • Interface TouchEvent

This interface defines the touchstart, touchend, touchmove, touchenter, touchleave, and touchcancel event types.
interface TouchEvent : UIEvent {
readonly attribute TouchList touches;
readonly attribute TouchList targetTouches;
readonly attribute TouchList changedTouches;
void initTouchEvent (in DOMString type, in boolean canBubble, in boolean cancelable, in DOMWindow view, in long detail,
  in boolean ctrlKey, in boolean altKey, in boolean shiftKey, in boolean metaKey, in TouchList touches, in TouchList targetTouches,
  in TouchList changedTouches);
};
Attribute
  1. changedTouches: Its a list of TouchPoints for every point of contact which contributed to the event.
  2. targetTouches :Its a list of TouchPoints for every point of contact currently touching the surface, which started on the same target.
  3. touches:Its a list of TouchPoints for every point of contact currently touching the surface.

Methods
  1. initTouchEvent: initializes a TouchEvent created through the DocumentEvent interface.

XUL events

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
Mouse DOMMouseScroll DOMMouseScroll Fires when the mouse wheel is moved, causing the content to scroll. Yes Yes
dragdrop ondragdrop Fires when the user releases the mouse button to drop an object being dragged. No No
dragenter ondragenter Fires when the mouse pointer first moves over an element during a drag. It is similar to the mouseover event but occurs while dragging. No No
dragexit ondragexit Fires when the mouse pointer moves away from an element during a drag. It is also called after a drop on an element. It is similar to the mouseout event but occurs during a drag. No No
draggesture ondraggesture Fires when the user starts dragging the element, usually by holding down the mouse button and moving the mouse. No No
dragover ondragover Related to the mousemove event, this event is fired while something is being dragged over an element. No No
Input CheckboxStateChange Fires when a checkbox is checked or unchecked, either by the user or a script. No No
RadioStateChange Fires when a radio button is selected, either by the user or a script. No No
close onclose Fires when a request has been made to close the window. No Yes
command oncommand Similar to W3C DOMActivate event. Fires when an element is activated, for instance, through a mouse click or a keypress. No No
input oninput Fires when a user enters text in a textbox. No No
User interface DOMMenuItemActive DOMMenuItemActive Fires when a menu or menuitem is hovered over, or highlighted. Yes No
DOMMenuItemInactive DOMMenuItemInactive Fires when a menu or menuitem is no longer being hovered over, or highlighted. Yes No
contextmenu oncontextmenu Fires when the user requests to open the context menu for the element. The action to do this varies by platform, but it will typically be a right click. No Yes
overflow onoverflow Fires a box or other layout element when there is not enough space to display it at full size. No No
overflowchanged onoverflowchanged Fires when the overflow state changes. No No
underflow onunderflow Fires to an element when there becomes enough space to display it at full size. No No
popuphidden onpopuphidden Fires to a popup after it has been hidden. No No
popuphiding onpopuphiding Fires to a popup when it is about to be hidden. No No
popupshowing onpopupshowing Fires to a popup just before it is popped open. No Yes
popupshown onpopupshown Fires to a popup after it has been opened, much like the onload event is sent to a window when it is opened. No No
Command broadcast onbroadcast Placed on an observer. The broadcast event is sent when the attributes of the broadcaster being listened to are changed. No No
commandupdate oncommandupdate Fires when a command update occurs. No No

Other events

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
HTML 5
HTML5 is a language for structuring and presenting content for the World Wide Web, and is a core technology of the Internet originally proposed by Opera Software. It is the fifth revision of the HTML standard and is still under development...

 Draft Specification.
The "DOMContentLoaded" event was also implemented in the Webkit
WebKit
WebKit is a layout engine designed to allow web browsers to render web pages. WebKit powers Google Chrome and Apple Safari and by October 2011 held over 33% of the browser market share between them. It is also used as the basis for the experimental browser included with the Amazon Kindle ebook...

 rendering engine build 500+. This correlates to all versions of Google Chrome
Google Chrome
Google Chrome is a web browser developed by Google that uses the WebKit layout engine. It was first released as a beta version for Microsoft Windows on September 2, 2008, and the public stable release was on December 11, 2008. The name is derived from the graphical user interface frame, or...

 and Safari
Safari (web browser)
Safari is a web browser developed by Apple Inc. and included with the Mac OS X and iOS operating systems. First released as a public beta on January 7, 2003 on the company's Mac OS X operating system, it became Apple's default browser beginning with Mac OS X v10.3 "Panther". Safari is also the...

 3.1+. DOMContentLoaded will be implemented in Internet Explorer 9.

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

Event flow

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
    Netscape Navigator
    Netscape Navigator was a proprietary web browser that was popular in the 1990s. It was the flagship product of the Netscape Communications Corporation and the dominant web browser in terms of usage share, although by 2002 its usage had almost disappeared...

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

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
DOMString type The name of the event (case-insensitive).
EventTarget target Used to indicate the EventTarget to which the event was originally dispatched.
EventTarget currentTarget Used to indicate the EventTarget whose EventListeners are currently being processed.
unsigned short eventPhase Used to indicate which phase of event flow is currently being evaluated.
boolean bubbles Used to indicate whether or not an event is a bubbling event.
boolean cancelable Used to indicate whether or not an event can have its default action prevented.
DOMTimeStamp timeStamp Used to specify the time (in milliseconds relative to the epoch) at which the event was created.

Event methods
Name Argument type Argument name Description
stopPropagation To prevent further propagation of an event during event flow.
preventDefault To cancel the event if it is cancelable, meaning that any default action normally taken by the implementation as a result of the event will not occur.
initEvent DOMString eventTypeArg Specifies the event type.
boolean canBubbleArg Specifies whether or not the event can bubble.
boolean cancelableArg Specifies whether or not the event's default action can be prevented.

DOM Level 0

This event handling model was introduced by Netscape Navigator, and remains the most cross-browser model . There are two model types: inline model and traditional model.

Inline model

In the inline model, event handlers are added as attribute of element. Event handlers can also be removed:





Hello Joe!




In the example above, an alert dialog box
Alert dialog box
An alert dialog is a colloquial term for a particular type of dialog box that occurs in a graphical user interface. It is also known as an alert box, alert window, error dialog, alert popup or plainly alert.The typical alert dialog provides information in a separate box to the user, after which...

 with the message "Hello Joe" will appear when the hyperlink
Hyperlink
In computing, a hyperlink is a reference to data that the reader can directly follow, or that is followed automatically. A hyperlink points to a whole document or to a specific element within a document. Hypertext is text with hyperlinks...

 is clicked and open URI in href attribute.

The default action can be cancelled by returning false in the event handler:





Stay here!




In the example above, the browser will not go to "example.com" when the hyperlink is clicked.

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 helloWorld 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
Anonymous function
In programming language theory, an anonymous function is a function defined, and possibly called, without being bound to an identifier. Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions such as Haskell...

 containing the statements in the onclick attribute. The onclick handler of the element would be bound to the following anonymous function:


function
{
helloWorld('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
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

.

Traditional model

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





Hello World!




To add parameters:

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


Inner functions preserve their scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...

.

DOM Level 2

The W3C designed a more flexible event handling model in DOM Level 2.
Name Description Argument type Argument name
addEventListener Allows the registration of event listeners on the event target. DOMString type
EventListener listener
boolean useCapture
removeEventListener Allows the removal of event listeners from the event target. DOMString type
EventListener listener
boolean useCapture
dispatchEvent Allows to send the event to the subscribed event listeners. Event evt


Some useful things to know :
  • To prevent an event from bubbling, developers must call the "stopPropagation" method of the event object.
  • To prevent the default action of the event to be called, developers must call the "preventDefault" method of the event object.


The main difference from the traditional model is that multiple event handlers can be registered for the same event. The useCapture option can also be used to specify that the handler should be called in the capture phase instead of the bubbling phase. This model is supported by Mozilla
Mozilla
Mozilla is a term used in a number of ways in relation to the Mozilla.org project and the Mozilla Foundation, their defunct commercial predecessor Netscape Communications Corporation, and their related application software....

, Opera, Safari
Safari (web browser)
Safari is a web browser developed by Apple Inc. and included with the Mac OS X and iOS operating systems. First released as a public beta on January 7, 2003 on the company's Mac OS X operating system, it became Apple's default browser beginning with Mac OS X v10.3 "Panther". Safari is also the...

, Chrome
Google Chrome
Google Chrome is a web browser developed by Google that uses the WebKit layout engine. It was first released as a beta version for Microsoft Windows on September 2, 2008, and the public stable release was on December 11, 2008. The name is derived from the graphical user interface frame, or...

 and Konqueror
Konqueror
Not to be confused with the Conqueror web browser.Konqueror is a web browser and file manager that provides file-viewer functionality for file systems such as local files, files on a remote ftp server and files in a disk image. It is a core part of the KDE desktop environment...

.

A rewrite of the example used in traditional model:





Hello World!



Microsoft-specific model

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.
Name Description Argument type Argument name
attachEvent Similar to W3C's addEventListener method. String sEvent
Pointer fpNotify
detachEvent Similar to W3C's removeEventListener method. String sEvent
Pointer fpNotify
fireEvent Similar to W3C's dispatchEvent method. String sEvent
Event oEventObject


Some useful things to know :
  • To prevent an event bubbling, developers must set the event's "cancelBubble" property.
  • To prevent the default action of the event to be called, developers must set the event's "returnValue" property.
  • The this keyword refers to the global window object.


Again, this model differs from the traditional model in that multiple event handlers can be registered for the same event. However the useCapture option can not be used to specify that the handler should be called in the capture phase. This model is supported by Microsoft Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...

 and Trident based browsers (e.g. Maxthon
Maxthon
Maxthon is a free web browser for Microsoft Windows. The latest release, Maxthon 3, supports both the Trident and the WebKit rendering engines....

, Avant Browser
Avant Browser
Avant Browser is a freeware web browser from a Chinese programmer named Anderson Che, which unites the Trident layout engine built into Windows with an interface intended to be more feature-rich, flexible and ergonomic than Microsoft's Internet Explorer . It runs on Windows 2000 and above,...

).

A rewrite of the example used in traditional model:





Hello World!



External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK