Mouse Events

Editor’s Draft,

More details about this document
This version:
https://w3c.github.io/uievents/
Latest published version:
https://www.w3.org/TR/uievents/
Feedback:
GitHub
Editors:
(Google)
(Microsoft)
Former Editor:
Doug Schepers (Mar 2008 - May 2011)
Tests:
web-platform-tests uievents/ (ongoing work)

Abstract

*** Mouse Events ***

Note: This is an experimental split of the UI Events spec into smaller, event-specific specs. The split was made from an out-of-date snapshot, so the information here is not current, so please focus on the overall structure rather than the specifics of the content. If this experiment goes well, then we will split the current spec after all outstanding pull requests have been handled.

Status of this document

This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document was published by the Web Applications Working Group as an Editors Draft. This document is intended to become a W3C Recommendation.

This document was published by the Web Applications Working Group as a Working Draft. Feedback and comments on this specification are welcome. Please use GitHub issues Historical discussions can be found in the public-webapps@w3.org archives.

Publication as an Editors Draft does not imply endorsement by W3C and its Members. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 2 November 2021 W3C Process Document.

1. Introduction

1.1. Overview

TODO.

1.2. Conformance

Boilerplate?

2. Stylistic Conventions

This specification follows the Proposed W3C Specification Conventions, with the following supplemental additions:

This is a note.

This is an open issue.

This is a warning.

interface Example {
    // This is an IDL definition.
};

3. Mouse Events

The mouse event module originates from the [HTML401] onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, and onmouseout attributes. This event module is specifically designed for use with pointing input devices, such as a mouse or a trackball.

3.1. Interface MouseEvent

Introduced in DOM Level 2, modified in this specification

The MouseEvent interface provides specific contextual information associated with Mouse events.

In the case of nested elements, mouse events are always targeted at the most deeply nested element.

Ancestors of the targeted element can use event bubbling to obtain notifications of mouse events which occur within their descendent elements.

To create an instance of the MouseEvent interface, use the MouseEvent constructor, passing an optional MouseEventInit dictionary.

When initializing MouseEvent objects using initMouseEvent, implementations can use the client coordinates clientX and clientY for calculation of other coordinates (such as target coordinates exposed by DOM Level 0 implementations or other proprietary attributes, e.g., pageX).

3.1.1. MouseEvent

[Exposed=Window]
interface MouseEvent : UIEvent {
  constructor(DOMString type, optional MouseEventInit eventInitDict = {});
  readonly attribute long screenX;
  readonly attribute long screenY;
  readonly attribute long clientX;
  readonly attribute long clientY;
  readonly attribute long layerX;
  readonly attribute long layerY;

  readonly attribute boolean ctrlKey;
  readonly attribute boolean shiftKey;
  readonly attribute boolean altKey;
  readonly attribute boolean metaKey;

  readonly attribute short button;
  readonly attribute unsigned short buttons;

  readonly attribute EventTarget? relatedTarget;

  boolean getModifierState(DOMString keyArg);
};
screenX, of type long, readonly
The horizontal coordinate at which the event occurred relative to the origin of the screen coordinate system.

The un-initialized value of this attribute MUST be 0.

screenY, of type long, readonly
The vertical coordinate at which the event occurred relative to the origin of the screen coordinate system.

The un-initialized value of this attribute MUST be 0.

clientX, of type long, readonly
The horizontal coordinate at which the event occurred relative to the viewport associated with the event.

The un-initialized value of this attribute MUST be 0.

clientY, of type long, readonly
The vertical coordinate at which the event occurred relative to the viewport associated with the event.

The un-initialized value of this attribute MUST be 0.

layerX, of type long, readonly
The horizontal offset from the nearest ancestor element which is a stacking context, is positioned, or paints in the positioned phase when painting a stacking context.

The un-initialized value of this attribute MUST be 0.

layerY, of type long, readonly
The vertical offset from the nearest ancestor element which is a stacking context, is positioned, or paints in the positioned phase when painting a stacking context.

The un-initialized value of this attribute MUST be 0.

ctrlKey, of type boolean, readonly
Refer to the KeyboardEvent's ctrlKey attribute.

The un-initialized value of this attribute MUST be false.

shiftKey, of type boolean, readonly
Refer to the KeyboardEvent's shiftKey attribute.

The un-initialized value of this attribute MUST be false.

altKey, of type boolean, readonly
Refer to the KeyboardEvent's altKey attribute.

The un-initialized value of this attribute MUST be false.

metaKey, of type boolean, readonly
Refer to the KeyboardEvent's metaKey attribute.

The un-initialized value of this attribute MUST be false.

button, of type short, readonly
During mouse events caused by the depression or release of a mouse button, button MUST be used to indicate which pointer device button changed state.

The value of the button attribute MUST be as follows:

  • 0 MUST indicate the primary button of the device (in general, the left button or the only button on single-button devices, used to activate a user interface control or select text) or the un-initialized value.

  • 1 MUST indicate the auxiliary button (in general, the middle button, often combined with a mouse wheel).

  • 2 MUST indicate the secondary button (in general, the right button, often used to display a context menu).

  • 3 MUST indicate the X1 (back) button.

  • 4 MUST indicate the X2 (forward) button.

Some pointing devices provide or simulate more button states, and values higher than 2 or lower than 0 MAY be used to represent such buttons.

The value of button is not updated for events not caused by the depression/release of a mouse button. In these scenarios, take care not to interpret the value 0 as the left button, but rather as the un-initialized value.

Some default actions related to events such as mousedown and mouseup depend on the specific mouse button in use.

The un-initialized value of this attribute MUST be 0.

buttons, of type unsigned short, readonly
During any mouse events, buttons MUST be used to indicate which combination of mouse buttons are currently being pressed, expressed as a bitmask.

Though similarly named, the values for the buttons attribute and the button attribute are very different. The value of button is assumed to be valid during mousedown / mouseup event handlers, whereas the buttons attribute reflects the state of the mouse’s buttons for any trusted MouseEvent object (while it is being dispatched), because it can represent the "no button currently active" state (0).

The value of the buttons attribute MUST be as follows:

  • 0 MUST indicate no button is currently active.

  • 1 MUST indicate the primary button of the device (in general, the left button or the only button on single-button devices, used to activate a user interface control or select text).

  • 2 MUST indicate the secondary button (in general, the right button, often used to display a context menu), if present.

  • 4 MUST indicate the auxiliary button (in general, the middle button, often combined with a mouse wheel).

Some pointing devices provide or simulate more buttons. To represent such buttons, the value MUST be doubled for each successive button (in the binary series 8, 16, 32, ... ).

Because the sum of any set of button values is a unique number, a content author can use a bitwise operation to determine how many buttons are currently being pressed and which buttons they are, for an arbitrary number of mouse buttons on a device. For example, the value 3 indicates that the left and right button are currently both pressed, while the value 5 indicates that the left and middle button are currently both pressed.

Some default actions related to events such as mousedown and mouseup depend on the specific mouse button in use.

The un-initialized value of this attribute MUST be 0.

relatedTarget, of type EventTarget, readonly, nullable
Used to identify a secondary EventTarget related to a UI event, depending on the type of event.

The un-initialized value of this attribute MUST be null.

getModifierState(keyArg)

Introduced in this specification

Queries the state of a modifier using a key value.

Returns true if it is a modifier key and the modifier is activated, false otherwise.

DOMString keyArg
Refer to the KeyboardEvent's getModifierState() method for a description of this parameter.

3.1.2. MouseEventInit

dictionary MouseEventInit : EventModifierInit {
  long screenX = 0;
  long screenY = 0;
  long clientX = 0;
  long clientY = 0;

  short button = 0;
  unsigned short buttons = 0;
  EventTarget? relatedTarget = null;
};
screenX, of type long, defaulting to 0
Initializes the screenX attribute of the MouseEvent object to the desired horizontal relative position of the mouse pointer on the user’s screen.

Initializing the event object to the given mouse position must not move the user’s mouse pointer to the initialized position.

screenY, of type long, defaulting to 0
Initializes the screenY attribute of the MouseEvent object to the desired vertical relative position of the mouse pointer on the user’s screen.

Initializing the event object to the given mouse position must not move the user’s mouse pointer to the initialized position.

clientX, of type long, defaulting to 0
Initializes the clientX attribute of the MouseEvent object to the desired horizontal position of the mouse pointer relative to the client window of the user’s browser.

Initializing the event object to the given mouse position must not move the user’s mouse pointer to the initialized position.

clientY, of type long, defaulting to 0
Initializes the clientY attribute of the MouseEvent object to the desired vertical position of the mouse pointer relative to the client window of the user’s browser.

Initializing the event object to the given mouse position must not move the user’s mouse pointer to the initialized position.

button, of type short, defaulting to 0
Initializes the button attribute of the MouseEvent object to a number representing the desired state of the button(s) of the mouse.

The value 0 is used to represent the primary mouse button, 1 is used to represent the auxiliary/middle mouse button, and 2 to represent the right mouse button. Numbers greater than 2 are also possible, but are not specified in this document.

buttons, of type unsigned short, defaulting to 0
Initializes the buttons attribute of the MouseEvent object to a number representing one or more of the button(s) of the mouse that are to be considered active.

The buttons attribute is a bit-field. If a mask value of 1 is true when applied to the value of the bit field, then the primary mouse button is down. If a mask value of 2 is true when applied to the value of the bit field, then the right mouse button is down. If a mask value of 4 is true when applied to the value of the bit field, then the auxiliary/middle button is down.

In JavaScript, to initialize the buttons attribute as if the right (2) and middle button (4) were being pressed simultaneously, the buttons value can be assigned as either:
  { buttons: 2 | 4 }
or:
  { buttons: 6 }

relatedTarget, of type EventTarget, nullable, defaulting to null
The relatedTarget should be initialized to the element whose bounds the mouse pointer just left (in the case of a mouseover or mouseenter event) or the element whose bounds the mouse pointer is entering (in the case of a mouseout or mouseleave or focusout event). For other events, this value need not be assigned (and will default to null).

Implementations MUST maintain the current click count when generating mouse events. This MUST be a non-negative integer indicating the number of consecutive clicks of a pointing device button within a specific time. The delay after which the count resets is specific to the environment configuration.

3.2. Event Modifier Initializers

The MouseEvent and KeyboardEvent interfaces share a set of keyboard modifier attributes and support a mechanism for retrieving additional modifier states. The following dictionary enables authors to initialize keyboard modifier attributes of the MouseEvent and KeyboardEvent interfaces, as well as the additional modifier states queried via getModifierState(). The steps for constructing events using this dictionary are defined in the event constructors section.

dictionary EventModifierInit : UIEventInit {
  boolean ctrlKey = false;
  boolean shiftKey = false;
  boolean altKey = false;
  boolean metaKey = false;

  boolean modifierAltGraph = false;
  boolean modifierCapsLock = false;
  boolean modifierFn = false;
  boolean modifierFnLock = false;
  boolean modifierHyper = false;
  boolean modifierNumLock = false;
  boolean modifierScrollLock = false;
  boolean modifierSuper = false;
  boolean modifierSymbol = false;
  boolean modifierSymbolLock = false;
};
ctrlKey, of type boolean, defaulting to false
Initializes the ctrlKey attribute of the MouseEvent or KeyboardEvent objects to true if the Control key modifier is to be considered active, false otherwise.

When true, implementations must also initialize the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Control must return true.

shiftKey, of type boolean, defaulting to false
Initializes the shiftKey attribute of the MouseEvent or KeyboardEvent objects to true if the Shift key modifier is to be considered active, false otherwise.

When true, implementations must also initialize the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Shift must return true.

altKey, of type boolean, defaulting to false
Initializes the altKey attribute of the MouseEvent or KeyboardEvent objects to true if the Alt (alternative) (or Option) key modifier is to be considered active, false otherwise.

When true, implementations must also initialize the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Alt must return true.

metaKey, of type boolean, defaulting to false
Initializes the metaKey attribute of the MouseEvent or KeyboardEvent objects to true if the Meta key modifier is to be considered active, false otherwise.

When true, implementations must also initialize the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with either the parameter Meta must return true.

modifierAltGraph, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter AltGraph must return true.
modifierCapsLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter CapsLock must return true.
modifierFn, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Fn must return true.
modifierFnLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter FnLock must return true.
modifierHyper, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Hyper must return true.
modifierNumLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter NumLock must return true.
modifierScrollLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter ScrollLock must return true.
modifierSuper, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Super must return true.
modifierSymbol, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Symbol must return true.
modifierSymbolLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter SymbolLock must return true.

3.3. Mouse Event Order

Certain mouse events defined in this specification MUST occur in a set order relative to one another. The following shows the event sequence that MUST occur when a pointing device’s cursor is moved over an element:

Event Type Element Notes
1 mousemove
Pointing device is moved into element A...
2 mouseover A
3 mouseenter A
4 mousemove A Multiple mousemove events
Pointing device is moved out of element A...
5 mouseout A
6 mouseleave A

When a pointing device is moved into an element A, and then into a nested element B and then back out again, the following sequence of events MUST occur:

Event Type Element Notes
1 mousemove
Pointing device is moved into element A...
2 mouseover A
3 mouseenter A
4 mousemove A Multiple mousemove events
Pointing device is moved into nested element B...
5 mouseout A
6 mouseover B
7 mouseenter B
8 mousemove B Multiple mousemove events
Pointing device is moved from element B into A...
9 mouseout B
10 mouseleave B
11 mouseover A
12 mousemove A Multiple mousemove events
Pointing device is moved out of element A...
13 mouseout A
14 mouseleave A

Sometimes elements can be visually overlapped using CSS. In the following example, three elements labeled A, B, and C all have the same dimensions and absolute position on a web page. Element C is a child of B, and B is a child of A in the DOM:

Graphical representation of three stacked elements all on top of each other. The bottom element is labeled A and the top element is C
Graphical representation of three stacked elements all on top of each other, with the pointing device moving over the stack.

When the pointing device is moved from outside the element stack to the element labeled C and then moved out again, the following series of events MUST occur:

Event Type Element Notes
1 mousemove
Pointing device is moved into element C, the topmost element in the stack
2 mouseover C
3 mouseenter A
4 mouseenter B
5 mouseenter C
6 mousemove C Multiple mousemove events
Pointing device is moved out of element C...
7 mouseout C
8 mouseleave C
9 mouseleave B
10 mouseleave A

The mouseover/mouseout events are only fired once, while mouseenter/mouseleave events are fired three times (once to each element).

The following is the typical sequence of events when a button associated with a pointing device (e.g., a mouse button or trackpad) is pressed and released over an element:

Event Type Notes
1 mousedown
2 mousemove OPTIONAL, multiple events, some limits
3 mouseup
4 click
5 mousemove OPTIONAL, multiple events, some limits
6 mousedown
7 mousemove OPTIONAL, multiple events, some limits
8 mouseup
9 click
10 dblclick

The lag time, degree, distance, and number of mousemove events allowed between the mousedown and mouseup events while still firing a click or dblclick event will be implementation-, device-, and platform-specific. This tolerance can aid users that have physical disabilities like unsteady hands when these users interact with a pointing device.

Each implementation will determine the appropriate hysteresis tolerance, but in general SHOULD fire click and dblclick events when the event target of the associated mousedown and mouseup events is the same element with no mouseout or mouseleave events intervening, and SHOULD fire click and dblclick events on the nearest common inclusive ancestor when the associated mousedown and mouseup event targets are different.

If a mousedown event was targeted at an HTML document’s body element, and the corresponding mouseup event was targeted at the root element, then the click event will be dispatched to the root element, since it is the nearest common inclusive ancestor.

If the event target (e.g. the target element) is removed from the DOM during the mouse events sequence, the remaining events of the sequence MUST NOT be fired on that element.

If the target element is removed from the DOM as the result of a mousedown event, no events for that element will be dispatched for mouseup, click, or dblclick, nor any default activation events. However, the mouseup event will still be dispatched on the element that is exposed to the mouse after the removal of the initial target element. Similarly, if the target element is removed from the DOM during the dispatch of a mouseup event, the click and subsequent events will not be dispatched.

3.4. Mouse Event Types

The Mouse event types are listed below. In the case of nested elements, mouse event types are always targeted at the most deeply nested element. Ancestors of the targeted element MAY use bubbling to obtain notification of mouse events which occur within its descendent elements.

3.4.1. auxclick

Type auxclick
Interface PointerEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action Varies
Context
(trusted events)

The auxclick event type MUST be dispatched on the topmost event target indicated by the pointer, when the user presses down and releases the non-primary pointer button, or otherwise activates the pointer in a manner that simulates such an action. The actuation method of the mouse button depends upon the pointer device and the environment configuration, e.g., it MAY depend on the screen location or the delay between the press and release of the pointing device button.

The auxclick event should only be fired for the non-primary pointer buttons (i.e., when button value is not 0, buttons value is greater than 1). The primary button (like the left button on a standard mouse) MUST NOT fire auxclick events. See click for a corresponding event that is associated with the primary button.

The auxclick event MAY be preceded by the mousedown and mouseup events on the same element, disregarding changes between other node types (e.g., text nodes). Depending upon the environment configuration, the auxclick event MAY be dispatched if one or more of the event types mouseover, mousemove, and mouseout occur between the press and release of the pointing device button.

The default action of the auxclick event type varies based on the event target of the event and the value of the button or buttons attributes. Typical default actions of the auxclick event type are as follows:

Receiving and handling auxclick for the middle button.
myLink.addEventListener("auxclick", function(e) { if (e.button === 1) { // This would prevent the default behavior which is for example // opening a new tab when middle clicking on a link. e.preventDefault(); // Do something else to handle middle button click like taking // care of opening link or non-link buttons in new tabs in a way // that fits the app. Other actions like closing a tab in a tab-strip // which should be done on the click action can be done here too. } });

In the case of right button, the auxclick event is dispatched after any contextmenu event. Note that some user agents swallow all input events while a context menu is being displayed, so auxclick may not be available to applications in such scenarios. See this example for more clarification.

Receiving and handling auxclick for the right button
myDiv.addEventListener("contextmenu", function(e) { // This call makes sure no context menu is shown // to interfere with page receiving the events. e.preventDefault(); }); myDiv.addEventListener("auxclick", function(e) { if (e.button === 2) { // Do something else to handle right button click like opening a // customized context menu inside the app. } });

3.4.2. click

Type click
Interface PointerEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action Varies
Context
(trusted events)

The click event type MUST be dispatched on the topmost event target indicated by the pointer, when the user presses down and releases the primary pointer button, or otherwise activates the pointer in a manner that simulates such an action. The actuation method of the mouse button depends upon the pointer device and the environment configuration, e.g., it MAY depend on the screen location or the delay between the press and release of the pointing device button.

The click event should only be fired for the primary pointer button (i.e., when button value is 0, buttons value is 1). Secondary buttons (like the middle or right button on a standard mouse) MUST NOT fire click events. See auxclick for a corresponding event that is associated with the non-primary buttons.

The click event MAY be preceded by the mousedown and mouseup events on the same element, disregarding changes between other node types (e.g., text nodes). Depending upon the environment configuration, the click event MAY be dispatched if one or more of the event types mouseover, mousemove, and mouseout occur between the press and release of the pointing device button. The click event MAY also be followed by the dblclick event.

If a user mouses down on a text node child of a <p> element which has been styled with a large line-height, shifts the mouse slightly such that it is no longer over an area containing text but is still within the containing block of that <p> element (i.e., the pointer is between lines of the same text block, but not over the text node per se), then subsequently mouses up, this will likely still trigger a click event (if it falls within the normal temporal hysteresis for a click), since the user has stayed within the scope of the same element. Note that user-agent-generated mouse events are not dispatched on text nodes.

In addition to being associated with pointer devices, the click event type MUST be dispatched as part of an element activation, as described in § 8.1.1 Activation triggers and behavior.

For maximum accessibility, content authors are encouraged to use the click event type when defining activation behavior for custom controls, rather than other pointing-device event types such as mousedown or mouseup, which are more device-specific. Though the click event type has its origins in pointer devices (e.g., a mouse), subsequent implementation enhancements have extended it beyond that association, and it can be considered a device-independent event type for element activation.

The default action of the click event type varies based on the event target of the event and the value of the button or buttons attributes. Typical default actions of the click event type are as follows:

3.4.3. contextmenu

Type contextmenu
Interface PointerEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action Invoke a context menu if supported.
Context
(trusted events)

A user agent MUST dispatch this event before invoking a context menu.

When the contextmenu event is triggered by right mouse button, the contextmenu event MUST be dispatched after the mousedown event.

Depending on the platform, the contextmenu event may be dispatched before or after the mouseup event.

3.4.4. dblclick

Type dblclick
Interface MouseEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when the primary button of a pointing device is clicked twice over an element. The definition of a double click depends on the environment configuration, except that the event target MUST be the same between mousedown, mouseup, and dblclick. This event type MUST be dispatched after the event type click if a click and double click occur simultaneously, and after the event type mouseup otherwise.

As with the click event, the dblclick event should only be fired for the primary pointer button. Secondary buttons MUST NOT fire dblclick events.

Canceling the click event does not affect the firing of a dblclick event.

As with the click event type, the default action of the dblclick event type varies based on the event target of the event and the value of the button or buttons attributes. The typical default actions of the dblclick event type match those of the click event type.

3.4.5. mousedown

Type mousedown
Interface MouseEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action Varies: Start a drag/drop operation; start a text selection; start a scroll/pan interaction (in combination with the middle mouse button, if supported)
Context
(trusted events)

A user agent MUST dispatch this event when a pointing device button is pressed over an element.

Many implementations use the mousedown event to begin a variety of contextually dependent default actions. These default actions can be prevented if this event is canceled. Some of these default actions could include: beginning a drag/drop interaction with an image or link, starting text selection, etc. Additionally, some implementations provide a mouse-driven panning feature that is activated when the middle mouse button is pressed at the time the mousedown event is dispatched.

3.4.6. mouseenter

Type mouseenter
Interface MouseEvent
Sync / Async Sync
Bubbles No
Trusted Targets Element
Cancelable No
Composed No
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a pointing device is moved onto the boundaries of an element or one of its descendent elements. A user agent MUST also dispatch this event when the element or one of its descendants moves to be underneath the primary pointing device. This event type is similar to mouseover, but differs in that it does not bubble, and MUST NOT be dispatched when the pointer device moves from an element onto the boundaries of one of its descendent elements.

There are similarities between this event type and the CSS :hover pseudo-class [CSS2]. See also the mouseleave event type.

3.4.7. mouseleave

Type mouseleave
Interface MouseEvent
Sync / Async Sync
Bubbles No
Trusted Targets Element
Cancelable No
Composed No
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a pointing device is moved off of the boundaries of an element and all of its descendent elements. A user agent MUST also dispatch this event when the element or one of its descendants moves to be no longer underneath the primary pointing device. This event type is similar to mouseout, but differs in that does not bubble, and that it MUST NOT be dispatched until the pointing device has left the boundaries of the element and the boundaries of all of its children.

There are similarities between this event type and the CSS :hover pseudo-class [CSS2]. See also the mouseenter event type.

3.4.8. mousemove

Type mousemove
Interface MouseEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a pointing device is moved while it is over an element. The frequency rate of events while the pointing device is moved is implementation-, device-, and platform-specific, but multiple consecutive mousemove events SHOULD be fired for sustained pointer-device movement, rather than a single event for each instance of mouse movement. Implementations are encouraged to determine the optimal frequency rate to balance responsiveness with performance.

In some implementation environments, such as a browser, mousemove events can continue to fire if the user began a drag operation (e.g., a mouse button is pressed) and the pointing device has left the boundary of the user agent.

This event was formerly specified to be non-cancelable in DOM Level 2 Events, but was changed to reflect existing interoperability between user agents.

3.4.9. mouseout

Type mouseout
Interface MouseEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a pointing device is moved off of the boundaries of an element or when the element is moved to be no longer underneath the primary pointing device. This event type is similar to mouseleave, but differs in that does bubble, and that it MUST be dispatched when the pointer device moves from an element onto the boundaries of one of its descendent elements.

See also the mouseover event type.

3.4.10. mouseover

Type mouseover
Interface MouseEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a pointing device is moved onto the boundaries of an element or when the element is moved to be underneath the primary pointing device. This event type is similar to mouseenter, but differs in that it bubbles, and that it MUST be dispatched when the pointer device moves onto the boundaries of an element whose ancestor element is the event target for the same event listener instance.

See also the mouseout event type.

3.4.11. mouseup

Type mouseup
Interface MouseEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a pointing device button is released over an element.

In some implementation environments, such as a browser, a mouseup event can be dispatched even if the pointing device has left the boundary of the user agent, e.g., if the user began a drag operation with a mouse button pressed.

4. Constructing Mouse and Keyboard Events

Generally, when a constructor of an Event interface, or of an interface inherited from the Event interface, is invoked, the steps described in [DOM] should be followed. However the KeyboardEvent and MouseEvent interfaces provide additional dictionary members for initializing the internal state of the Event object’s key modifiers: specifically, the internal state queried for using the getModifierState() and getModifierState() methods. This section supplements the DOM4 steps for intializing a new Event object with these optional modifier states.

For the purposes of constructing a KeyboardEvent, MouseEvent, or object derived from these objects using the algorithm below, all KeyboardEvent, MouseEvent, and derived objects have internal key modifier state which can be set and retrieved using the key modifier names described in the Modifier Keys table in [UIEvents-Key].

The following steps supplement the algorithm defined for constructing events in DOM4:

5. Legacy Event Initializers

This section is normative.

The following features are obsolete and should only be implemented by user agents that require compatibility with legacy software.

Early versions of this specification included an initialization method on the interface (for example initMouseEvent) that required a long list of parameters that, in most cases, did not fully initialize all attributes of the event object. Because of this, event interfaces which were derived from the basic Event interface required that the initializer of each of the derived interfaces be called explicitly in order to fully initialize an event.

Initializing all the attributes of a MutationEvent requires calls to two initializer methods: initEvent and initMutationEvent.

Due in part to the length of time in the development of this standard, some implementations MAY have taken a dependency on these (now deprecated) initializer methods. For completeness, these legacy event initializers are described in this section.

5.1. Initializers for interface MouseEvent

This section is informative

partial interface MouseEvent {
  // Deprecated in this specification
  undefined initMouseEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional Window? viewArg = null,
    optional long detailArg = 0,
    optional long screenXArg = 0,
    optional long screenYArg = 0,
    optional long clientXArg = 0,
    optional long clientYArg = 0,
    optional boolean ctrlKeyArg = false,
    optional boolean altKeyArg = false,
    optional boolean shiftKeyArg = false,
    optional boolean metaKeyArg = false,
    optional short buttonArg = 0,
    optional EventTarget? relatedTargetArg = null);
};
initMouseEvent(typeArg)
Initializes attributes of a MouseEvent object. This method has the same behavior as UIEvent.initUIEvent().

The initMouseEvent method is deprecated, but supported for backwards-compatibility with widely-deployed implementations.

DOMString typeArg
Refer to the initEvent() method for a description of this parameter.
boolean bubblesArg
Refer to the initEvent() method for a description of this parameter.
boolean cancelableArg
Refer to the initEvent() method for a description of this parameter.
Window? viewArg
Specifies view. This value MAY be null.
long detailArg
Specifies detail.
long screenXArg
Specifies screenX.
long screenYArg
Specifies screenY.
long clientXArg
Specifies clientX.
long clientYArg
Specifies clientY.
boolean ctrlKeyArg
Specifies ctrlKey.
boolean altKeyArg
Specifies altKey.
boolean shiftKeyArg
Specifies shiftKey.
boolean metaKeyArg
Specifies metaKey.
short buttonArg
Specifies button.
EventTarget? relatedTargetArg
Specifies relatedTarget. This value MAY be null.

6. Security Considerations

TODO - Add specific concerns for this spec

7. Acknowledgements

TODO

8. Refs to other UIEvent specs [DELETE]

This section will be deleted.

Temporary place to "define" other referenced UI Events (to make the bikeshed linker happy). This will be deleted once we have proper cross-references.

8.1. Things defined in other sections

8.1.1. Activation triggers and behavior

8.1.2. Composition Events

8.1.3. Default actions and cancelable events

8.1.4. Event dispatch and DOM event flow

8.1.5. Web browsers and other dynamic or interactive user agents

8.1.6. Authoring tools

8.2. Things defined in KeyboardEvents

8.2.1. Modifier keys

9. Glossary [DELETE]

This section will be deleted.

Temporary glossary terms (for bikeshed linker). Many of these are properly defined elsewhere and should be linked to directly. Terms which should be defined in this spec should be defined inline.

activation behavior

The action taken when an event, typically initiated by users through an input device, causes an element to fulfill a defined task. The task MAY be defined for that element by the host language, or by author-defined variables, or both. The default task for any given element MAY be a generic action, or MAY be unique to that element. For example, the activation behavior of an HTML or SVG <a> element is to cause the user agent to traverse the link specified in the href attribute, with the further optional parameter of specifying the browsing context for the traversal (such as the current window or tab, a named window, or a new window). The activation behavior of an HTML <input> element with the type attribute value submit is be to send the values of the form elements to an author-defined IRI by the author-defined HTTP method. See § 8.1.1 Activation triggers and behavior for more details.

activation trigger

An event which is defined to initiate an activation behavior. Refer to § 8.1.1 Activation triggers and behavior for more details.

body element

In HTML or XHTML documents, the body element represents the contents of the document. In a well-formed HTML document, the body element is a first descendant of the root element.

DOM Level 0

The term DOM Level 0 refers to a mix of HTML document functionalities, often not formally specified but traditionally supported as de facto standards, implemented originally by Netscape Navigator version 3.0 or Microsoft Internet Explorer version 3.0. In many cases, attributes or methods have been included for reasons of backward compatibility with DOM Level 0.

default action

A default action is an OPTIONAL supplementary behavior that an implementation MUST perform in combination with the dispatch of the event object. Each event type definition, and each specification, defines the default action for that event type, if it has one. An instance of an event MAY have more than one default action under some circumstances, such as when associated with an activation trigger. A default action MAY be cancelled through the invocation of the preventDefault() method. For more details, see § 8.1.3 Default actions and cancelable events.

event

An event is the representation of some occurrence (such as a mouse click on the presentation of an element, the removal of child node from an element, or any number of other possibilities) which is associated with its event target. Each event is an instantiation of one specific event type.

event target

The object to which an event is targeted using the § 8.1.4 Event dispatch and DOM event flow. The event target is the value of the target attribute.

host language

Any language which integrates the features of another language or API specification, while normatively referencing the origin specification rather than redefining those features, and extending those features only in ways defined by the origin specification. An origin specification typically is only intended to be implemented in the context of one or more host languages, not as a standalone language. For example, XHTML, HTML, and SVG are host languages for UI Events, and they integrate and extend the objects and models defined in this specification.

hysteresis

A feature of human interface design to accept input values within a certain range of location or time, in order to improve the user experience. For example, allowing for small deviation in the time it takes for a user to double-click a mouse button is temporal hysteresis, and not immediately closing a nested menu if the user mouses out from the parent window when transitioning to the child menu is locative hysteresis.

topmost event target

The topmost event target MUST be the element highest in the rendering order which is capable of being an event target. In graphical user interfaces this is the element under the user’s pointing device. A user interface’s hit testing facility is used to determine the target. For specific details regarding hit testing and stacking order, refer to the host language.

un-initialized value

The value of any event attribute (such as bubbles or currentTarget) before the event has been initialized with initEvent(). The un-initialized values of an event apply immediately after a new event has been created using the method createEvent().

user agent

A program, such as a browser or content authoring tool, normally running on a client machine, which acts on a user’s behalf in retrieving, interpreting, executing, presenting, or creating content. Users MAY act on the content using different user agents at different times, for different purposes. See the § 8.1.5 Web browsers and other dynamic or interactive user agents and § 8.1.6 Authoring tools for details on the requirements for a conforming user agent.

Window

The Window is the object referred to by the current document’s browsing context’s Window Proxy object as defined in HTML5 [HTML5].

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Conformant Algorithms

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-DISPLAY-4]
CSS Display Module Level 4 URL: https://drafts.csswg.org/css-display-4/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[POINTEREVENTS3]
Patrick Lauke; Navid Zolghadr. Pointer Events. URL: https://w3c.github.io/pointerevents/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[UIEVENTS]
Gary Kacmarcik; Travis Leithead. UI Events. URL: https://w3c.github.io/uievents/
[WEBDRIVER-BIDI]
WebDriver BiDi URL: https://w3c.github.io/webdriver-bidi/
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL Standard. Living Standard. URL: https://webidl.spec.whatwg.org/

Informative References

[CSS2]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. URL: https://drafts.csswg.org/css2/
[HTML401]
Dave Raggett; Arnaud Le Hors; Ian Jacobs. HTML 4.01 Specification. 27 March 2018. REC. URL: https://www.w3.org/TR/html401/
[HTML5]
Ian Hickson; et al. HTML5. URL: https://www.w3.org/html/wg/drafts/html/master/
[UIEvents-Key]
Gary Kacmarcik; Travis Leithead. UI Events KeyboardEvent key Values. URL: https://w3c.github.io/uievents-key/

IDL Index

[Exposed=Window]
interface MouseEvent : UIEvent {
  constructor(DOMString type, optional MouseEventInit eventInitDict = {});
  readonly attribute long screenX;
  readonly attribute long screenY;
  readonly attribute long clientX;
  readonly attribute long clientY;
  readonly attribute long layerX;
  readonly attribute long layerY;

  readonly attribute boolean ctrlKey;
  readonly attribute boolean shiftKey;
  readonly attribute boolean altKey;
  readonly attribute boolean metaKey;

  readonly attribute short button;
  readonly attribute unsigned short buttons;

  readonly attribute EventTarget? relatedTarget;

  boolean getModifierState(DOMString keyArg);
};

dictionary MouseEventInit : EventModifierInit {
  long screenX = 0;
  long screenY = 0;
  long clientX = 0;
  long clientY = 0;

  short button = 0;
  unsigned short buttons = 0;
  EventTarget? relatedTarget = null;
};

dictionary EventModifierInit : UIEventInit {
  boolean ctrlKey = false;
  boolean shiftKey = false;
  boolean altKey = false;
  boolean metaKey = false;

  boolean modifierAltGraph = false;
  boolean modifierCapsLock = false;
  boolean modifierFn = false;
  boolean modifierFnLock = false;
  boolean modifierHyper = false;
  boolean modifierNumLock = false;
  boolean modifierScrollLock = false;
  boolean modifierSuper = false;
  boolean modifierSymbol = false;
  boolean modifierSymbolLock = false;
};

partial interface MouseEvent {
  // Deprecated in this specification
  undefined initMouseEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional Window? viewArg = null,
    optional long detailArg = 0,
    optional long screenXArg = 0,
    optional long screenYArg = 0,
    optional long clientXArg = 0,
    optional long clientYArg = 0,
    optional boolean ctrlKeyArg = false,
    optional boolean altKeyArg = false,
    optional boolean shiftKeyArg = false,
    optional boolean metaKeyArg = false,
    optional short buttonArg = 0,
    optional EventTarget? relatedTargetArg = null);
};