UI 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/
Previous Versions:
Feedback:
GitHub
Inline In Spec
Editors:
(Google)
(Microsoft)
Former Editor:
Doug Schepers (Mar 2008 - May 2011)
Tests:
web-platform-tests uievents/ (ongoing work)

Abstract

This specification defines UI Events which extend the DOM Event objects defined in [DOM]. UI Events are those typically implemented by visual user agents for handling user interaction such as mouse and keyboard input.

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 [email protected] 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 03 November 2023 W3C Process Document.

1. Introduction

1.1. Overview

UI Events is designed with two main goals. The first goal is the design of an event system which allows registration of event listeners and describes event flow through a tree structure. Additionally, the specification will provide standard modules of events for user interface control and document mutation notifications, including defined contextual information for each of these event modules.

The second goal of UI Events is to provide a common subset of the current event systems used in existing browsers. This is intended to foster interoperability of existing scripts and content. It is not expected that this goal will be met with full backwards compatibility. However, the specification attempts to achieve this when possible.

1.2. Conformance

This section is normative.

Within this specification, the key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT, RECOMMENDED, MAY, and OPTIONAL are to be interpreted as described in [RFC2119].

This specification is to be understood in the context of the DOM Level 3 Core specification [DOM-Level-3-Core] and the general considerations for DOM implementations apply. For example, handling of namespace URIs is discussed in XML Namespaces. For additional information about conformance, please see the DOM Level 3 Core specification [DOM-Level-3-Core]. A user agent is not required to conform to the entirety of another specification in order to conform to this specification, but it MUST conform to the specific parts of any other specification which are called out in this specification (e.g., a conforming UI Events user agent MUST support the DOMString data type as defined in [WebIDL], but need not support every method or data type defined in [WebIDL] in order to conform to UI Events).

This specification defines several classes of conformance for different user agents, specifications, and content authors:

1.2.1. Web browsers and other dynamic or interactive user agents

A dynamic or interactive user agent, referred to here as a browser (be it a Web browser, AT (Accessibility Technology) application, or other similar program), conforms to UI Events if it supports:

A conforming browser MUST dispatch events appropriate to the given EventTarget when the conditions defined for that event type have been met.

A browser conforms specifically to UI Events if it implements the interfaces and related event types specified in this document.

A conforming browser MUST support scripting, declarative interactivity, or some other means of detecting and dispatching events in the manner described by this specification, and MUST support the APIs specified for that event type.

In addition to meeting all other conformance criteria, a conforming browser MAY implement features of this specification marked as deprecated, for backwards compatibility with existing content, but such implementation is discouraged.

A conforming browser MAY also support features not found in this specification, but which use the interfaces, events, or other features defined in this specification, and MAY implement additional interfaces and event types appropriate to that implementation. Such features can be later standardized in future specifications.

A browser which does not conform to all required portions of this specification MUST NOT claim conformance to UI Events. Such an implementation which does conform to portions of this specification MAY claim conformance to those specific portions.

A conforming browser MUST also be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification [WebIDL].

1.2.2. Authoring tools

A content authoring tool conforms to UI Events if it produces content which uses the event types, consistent in a manner as defined in this specification.

A content authoring tool MUST NOT claim conformance to UI Events for content it produces which uses features of this specification marked as deprecated in this specification.

A conforming content authoring tool SHOULD provide to the content author a means to use all event types and interfaces appropriate to all host languages in the content document being produced.

1.2.3. Content authors and content

A content author creates conforming UI Events content if that content uses the event types consistent in a manner as defined in this specification.

A content author SHOULD NOT use features of this specification marked as deprecated, but SHOULD rely instead upon replacement mechanisms defined in this specification and elsewhere.

Conforming content MUST use the semantics of the interfaces and event types as described in this specification.

Content authors are advised to follow best practices as described in accessibility and internationalization guideline specifications.

1.2.4. Specifications and host languages

A specification or host language conforms to UI Events if it references and uses the event flow mechanism, interfaces, events, or other features defined in [DOM], and does not extend these features in incompatible ways.

A specification or host language conforms specifically to UI Events if it references and uses the interfaces and related event types specified in this document. A conforming specification MAY define additional interfaces and event types appropriate to that specification, or MAY extend the UI Events interfaces and event types in a manner that does not contradict or conflict with the definitions of those interfaces and event types in this specification.

Specifications or host languages which reference UI Events SHOULD NOT use or recommend features of this specification marked as deprecated, but SHOULD use or recommend the indicated replacement for that the feature (if available).

2. Stylistic Conventions

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

In addition, certain terms are used in this specification with particular meanings. The term implementation applies to a browser, content authoring tool, or other user agent that implements this specification, while a content author is a person who writes script or code that takes advantage of the interfaces, methods, attributes, events, and other features described in this specification in order to make Web applications, and a user is the person who uses those Web applications in an implementation.

And finally:

This is a note.

This is an open issue.

This is a warning.

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

3. Basic Event Interfaces

The basic event interfaces defined in [DOM] are fundamental to UI Events. These basic event interfaces MUST always be supported by the implementation:

The event types defined in this specification derive from these basic interfaces, and MUST inherit all of the attributes, methods, and constants of the interfaces they derive from.

The following chart describes the inheritance structure of the interfaces described in this specification.

Graphical representation of inheritance of interfaces defined by this specification
Graphical representation of inheritance of interfaces defined by this specification

3.1. List of Event Types

Each event MUST be associated with a type, called event type and available as the type attribute on the event object. The event type MUST be of type DOMString.

Depending on the level of DOM support, or the devices used for display (e.g., screen) or interaction (e.g., mouse, keyboard, touch screen, or voice), these event types can be generated by the implementation. When used with an [XML] or [HTML5] application, the specifications of those languages MAY restrict the semantics and scope (in particular the possible event targets) associated with an event type. Refer to the specification defining the language used in order to find those restrictions or to find event types that are not defined in this document.

The following table provides an informative summary of the event types described in this specification.

Event Type Sync / Async Bubbling Phase Trusted event target types DOM Interface Cancelable Default Action
abort Sync No Window, Element Event No None
auxclick Sync Yes Element PointerEvent Yes Varies
beforeinput Sync Yes Element InputEvent Yes Update the DOM element
blur Sync No Window, Element FocusEvent No None
click Sync Yes Element PointerEvent Yes Varies: for targets with an associated activation behavior, executes the activation behavior; for focusable targets, gives the element focus.
compositionstart Sync Yes Element CompositionEvent Yes Show a text composition system candidate window
compositionupdate Sync Yes Element CompositionEvent No None
compositionend Sync Yes Element CompositionEvent No None
contextmenu Sync Yes Element PointerEvent Yes Invoke a context menu if supported
dblclick Sync Yes Element MouseEvent No Varies: for targets with an associated activation behavior, executes the activation behavior; for focusable targets, gives the element focus.
error Async No Window, Element Event No None
focus Sync No Window, Element FocusEvent No None
focusin Sync Yes Window, Element FocusEvent No None
focusout Sync Yes Window, Element FocusEvent No None
input Sync Yes Element InputEvent No None
keydown Sync Yes Element KeyboardEvent Yes Varies: trigger beforeinput and input events; launch text composition system; blur and focus events; keypress event (if supported); activation behavior; other events
keyup Sync Yes Element KeyboardEvent Yes None
load Async No Window, Document, Element Event No None
mousedown Sync Yes Element MouseEvent Yes Varies: start a drag/drop operation; start a text selection; start a scroll/pan interaction (in combination with the middle mouse button, if supported)
mouseenter Sync No Element MouseEvent No None
mouseleave Sync No Element MouseEvent No None
mousemove Sync Yes Element MouseEvent Yes None
mouseout Sync Yes Element MouseEvent Yes None
mouseover Sync Yes Element MouseEvent Yes None
mouseup Sync Yes Element MouseEvent Yes None
select Sync Yes Element Event No None
unload Sync No Window, Document, Element Event No None
wheel Async Yes Element WheelEvent Yes Scroll (or zoom) the document

For a list of events which are deprecated in this specification, see the Legacy Event Types appendix at the end of this document.

The following is one way to interpret the above tables: the load event will trigger event listeners attached on Element nodes for that event and on the capture and target phases. This event is not cancelable. If an event listener for the load event is attached to a node other than Window, Document, or Element nodes, or if it is attached to the bubbling phase only, this event listener would not be triggered.

Don’t interpret the above tables as definitive for the listed event types. For example, the load event is used in other specifications, for example, in XMLHttpRequest. Similarly, dispatchEvent() can be used to dispatch untrusted events to listeners on any object that also implements EventTarget.

The event objects associated with the event types described above contain additional context information--refer to the description of the DOM interfaces for further information.

3.2. User Interface Events

The User Interface event module contains basic event types associated with user interfaces and document manipulation.

3.2.1. Interface UIEvent

Introduced in DOM Level 2

The UIEvent interface provides specific contextual information associated with User Interface events.

To create an instance of the UIEvent interface, use the UIEvent constructor, passing an optional UIEventInit dictionary.

For newly defined events, you don’t have to inherit UIEvent interface just because they are related to user interface. Inherit only when members of UIEventInit make sense to those events.

3.2.1.1. UIEvent
[Exposed=Window]
interface UIEvent : Event {
  constructor(DOMString type, optional UIEventInit eventInitDict = {});
  readonly attribute Window? view;
  readonly attribute long detail;
};
UIEvent . view
The view attribute identifies the Window from which the event was generated.

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

UIEvent . detail
Specifies some detail information about the Event, depending on the type of event.

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

3.2.1.2. UIEventInit
dictionary UIEventInit : EventInit {
  Window? view = null;
  long detail = 0;
};
UIEventInit . view
Should be initialized to the Window object of the global environment in which this event will be dispatched. If this event will be dispatched to an element, the view property should be set to the Window object containing the element’s ownerDocument.
UIEventInit . detail
This value is initialized to a number that is application-specific.

3.2.2. UIEvent Algorithms

3.2.2.1. initialize a UIEvent
Input

event, the UIEvent to initialize

eventType, a DOMString containing the event type

eventTarget, the EventTarget of the event

bubbles, true if this event bubbles

cancelable, true if this event is cancelable

Output

None

  1. Initialize the base Event attributes:

    1. Initialize an Event with event, eventType, bubbles and cancelable

    2. Set event.target = eventTarget

  2. Initialize the following public attributes:

    1. Set event.view = the eventTarget’s node document’s Window object

    2. Set event.detail = 0

  3. Initialize the following historical attributes:

    1. Set event.which = 0 (used by both MouseEvent and KeyboardEvent)

3.2.3. UIEvent Types

The User Interface event types are listed below. Some of these events use the UIEvent interface if generated from a user interface, but the Event interface otherwise, as detailed in each event.

3.2.3.1. load
Type load
Interface UIEvent if generated from a user interface, Event otherwise.
Sync / Async Async
Bubbles No
Trusted Targets Window, Document, Element
Cancelable No
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when the DOM implementation finishes loading the resource (such as the document) and any dependent resources (such as images, style sheets, or scripts). Dependent resources that fail to load MUST NOT prevent this event from firing if the resource that loaded them is still accessible via the DOM. If this event type is dispatched, implementations are REQUIRED to dispatch this event at least on the Document node.

For legacy reasons, load events for resources inside the document (e.g., images) do not include the Window in the propagation path in HTML implementations. See [HTML5] for more information.

3.2.3.2. unload
Type unload
Interface UIEvent if generated from a user interface, Event otherwise.
Sync / Async Sync
Bubbles No
Trusted Targets Window, Document, Element
Cancelable No
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when the DOM Implementation removes from the environment the resource (such as the document) or any dependent resources (such as images, style sheets, scripts). The document MUST be unloaded after the dispatch of this event type. If this event type is dispatched, implementations are REQUIRED to dispatch this event at least on the Document node.

3.2.3.3. abort
Type abort
Interface UIEvent if generated from a user interface, Event otherwise.
Sync / Async Sync
Bubbles No
Trusted Targets Window, Element
Cancelable No
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress.

3.2.3.4. error
Type error
Interface UIEvent if generated from a user interface, Event otherwise.
Sync / Async Async
Bubbles No
Trusted Targets Window, Element
Cancelable No
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a resource failed to load, or has been loaded but cannot be interpreted according to its semantics, such as an invalid image, a script execution error, or non-well-formed XML.

3.2.3.5. select
Type select
Interface UIEvent if generated from a user interface, Event otherwise.
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable No
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a user selects some text. This event is dispatched after the selection has occurred.

This specification does not provide contextual information to access the selected text. Where applicable, a host language SHOULD define rules for how a user MAY select content (with consideration for international language conventions), at what point the select event is dispatched, and how a content author MAY access the user-selected content.

In order to access to user-selected content, content authors will use native capabilities of the host languages, such as the Document.getSelection() method of the HTML Editing APIs [Editing].

The select event might not be available for all elements in all languages. For example, in [HTML5], select events can be dispatched only on form input and textarea elements. Implementations can dispatch select events in any context deemed appropriate, including text selections outside of form controls, or image or markup selections such as in SVG.

3.3. Focus Events

This interface and its associated event types and § 3.3.2 Focus Event Order were designed in accordance to the concepts and guidelines defined in User Agent Accessibility Guidelines 2.0 [UAAG20], with particular attention on the focus mechanism and the terms defined in the glossary entry for focus.

3.3.1. Interface FocusEvent

Introduced in this specification

The FocusEvent interface provides specific contextual information associated with Focus events.

To create an instance of the FocusEvent interface, use the FocusEvent constructor, passing an optional FocusEventInit dictionary.

3.3.1.1. FocusEvent
[Exposed=Window]
interface FocusEvent : UIEvent {
  constructor(DOMString type, optional FocusEventInit eventInitDict = {});
  readonly attribute EventTarget? relatedTarget;
};
FocusEvent . relatedTarget
Used to identify a secondary EventTarget related to a Focus event, depending on the type of event.

For security reasons with nested browsing contexts, when tabbing into or out of a nested context, the relevant EventTarget SHOULD be null.

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

3.3.1.2. FocusEventInit
dictionary FocusEventInit : UIEventInit {
  EventTarget? relatedTarget = null;
};
FocusEventInit . relatedTarget
The relatedTarget should be initialized to the element losing focus (in the case of a focus or focusin event) or the element gaining focus (in the case of a blur or focusout event).

3.3.2. Focus Event Order

The focus events defined in this specification occur in a set order relative to one another. The following is the typical sequence of events when a focus is shifted between elements (this order assumes that no element is initially focused):

Event Type Notes
User shifts focus
1 focus Sent after first target element receives focus
2 focusin Follows the focus event
User shifts focus
3 blur Sent after first target element loses focus
4 focusout Follows the blur event
5 focus Sent after second target element receives focus
6 focusin Follows the focus event

This specification does not define the behavior of focus events when interacting with methods such as focus() or blur(). See the relevant specifications where those methods are defined for such behavior.

3.3.3. Document Focus and Focus Context

This event module includes event types for notification of changes in document focus. There are three distinct focus contexts that are relevant to this discussion:

The event types defined in this specification deal exclusively with document focus, and the event target identified in the event details MUST only be part of the document or documents in the window, never a part of the browser or operating system, even when switching from one focus context to another.

Normally, a document always has a focused element (even if it is the document element itself) and a persistent focus ring. When switching between focus contexts, the document’s currently focused element and focus ring normally remain in their current state. For example, if a document has three focusable elements, with the second element focused, when a user changes operating system focus to another application and then back to the browser, the second element will still be focused within the document, and tabbing will change the focus to the third element. A host language MAY define specific elements which might receive focus, the conditions under which an element MAY receive focus, the means by which focus MAY be changed, and the order in which the focus changes. For example, in some cases an element might be given focus by moving a pointer over it, while other circumstances might require a mouse click. Some elements might not be focusable at all, and some might be focusable only by special means (clicking on the element), but not by tabbing to it. Documents MAY contain multiple focus rings. Other specifications MAY define a more complex focus model than is described in this specification, including allowing multiple elements to have the current focus.

3.3.4. Focus Event Types

The Focus event types are listed below.

3.3.4.1. blur
Type blur
Interface FocusEvent
Sync / Async Sync
Bubbles No
Trusted Targets Window, Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when an event target loses focus. The focus MUST be taken from the element before the dispatch of this event type. This event type is similar to focusout, but does not bubble.

3.3.4.2. focus
Type focus
Interface FocusEvent
Sync / Async Sync
Bubbles No
Trusted Targets Window, Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when an event target receives focus. The focus MUST be given to the element before the dispatch of this event type. This event type is similar to focusin, but does not bubble.

3.3.4.3. focusin
Type focusin
Interface FocusEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Window, Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when an event target receives focus. The event target MUST be the element which received focus. The focus event MUST fire before the dispatch of this event type. This event type is similar to focus, but does bubble.

3.3.4.4. focusout
Type focusout
Interface FocusEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Window, Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when an event target loses focus. The event target MUST be the element which lost focus. The blur event MUST fire before the dispatch of this event type. This event type is similar to blur, but does bubble.

3.4. 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.4.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.4.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.4.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.4.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 MouseEvent 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.4.2.1. Constructing Mouse 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 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() methods. This section supplements the DOM4 steps for intializing a new MouseEvent object with these optional modifier states.

For the purposes of constructing a MouseEvent, or object derived from these objects using the algorithm below, all 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:

3.4.3. MouseEvent Algorithms

3.4.3.1. Native OS Requirements

The algorithms in this section assume that the native platform OS will provide the following:

For these events, the OS will be able to provide the following info:

3.4.3.2. Global State for MouseEvent
3.4.3.2.1. User Agent-Level State

The UA must maintain the following values that are shared for the entire User Agent.

A mouse button bitmask that tracks the current state of the mouse buttons.

3.4.3.2.2. Window-Level State

The UA must maintain the following values that are shared for the Window.

A last mouse element value (initially undefined) that keeps track of the last Element that we sent a MouseEvent to.

A last mouse DOM path value (initially empty) that contains a snapshot of the ancestors Elements of the last mouse element when the most recent mouse event was sent.

3.4.3.3. Internal State for MouseEvent

A MouseEvent has the following internal flags that are used to track the state of various modifier keys: shift flag, control flag, alt flag, altgraph flag, and meta flag. These flags are set if the corresponding modifier key was pressed at the time of the mouse event.

3.4.3.4. initialize a MouseEvent
Input

event, the MouseEvent to initialize

eventType, a DOMString containing the event type

eventTarget, the EventTarget of the event

bubbles, true if this event bubbles

cancelable, true if this event is cancelable

Output

None

  1. Initialize a UIEvent with event, eventType, eventTarget, bubbles and cancelable.

  2. Initialize the following public attributes:

    1. Set event.screenX = the x-coordinate of the position where the event occurred relative to the origin of the desktop

    2. Set event.screenY = the y-coordinate of the position where the event occurred relative to the origin of the desktop

    3. Set event.clientX = the x-coordinate of the position where the event occurred relative to the origin of the viewport

    4. Set event.clientY = the y-coordinate of the position where the event occurred relative to the origin of the viewport

    5. Set mouse event modifiers with event

    6. Set event.button = 0

    7. Set event.buttons = mouse button bitmask

  3. Initialize PointerLock attributes for MouseEvent with event

3.4.3.5. set mouse event modifiers
Input

event, the MouseEvent to update

Output

None

  1. Set event’s shift flag if key modifier state includes "Shift", unset it otherwise

  2. Set event’s control flag if key modifier state includes "Control", unset it otherwise

  3. Set event’s alt flag if key modifier state includes "Alt", unset it otherwise

  4. Set event’s altgraph flag if key modifier state includes "AltGraph", unset it otherwise

  5. Set event’s meta flag if key modifier state includes "Meta", unset it otherwise

  6. Set event.shiftKey = true if the event’s shift flag is set, false otherwise

  7. Set event.ctrlKey = true if the event’s control flag is set, false otherwise

  8. Set event.altKey = true if the event’s alt flag or altgraph flag is set, false otherwise

  9. Set event.metaKey = true if the event’s meta flag is set, false otherwise

3.4.3.6. create a cancelable MouseEvent
Input

eventType, a DOMString containing a valid MouseEvent type

eventTarget, the EventTarget of the event

Output

None

  1. Let bubbles be "true"

  2. Let cancelable be "true"

  3. Let event = the result of creating a new event using MouseEvent

  4. Initialize a MouseEvent with event, eventType, eventTarget, bubbles and cancelable.

  5. Return event

3.4.3.7. create a non-cancelable MouseEvent
Input

eventType, a DOMString containing a valid MouseEvent type

eventTarget, the EventTarget of the event

Output

None

  1. Let bubbles be "false"

  2. Let cancelable be "false"

  3. Let event = the result of creating a new event using MouseEvent

  4. Initialize a MouseEvent with event, eventType, eventTarget, bubbles and cancelable.

  5. Return event

3.4.3.8. calculate MouseEvent button attribute
Input

mbutton, an ID that identifies a mouse button

Output

A button ID suitable for storing in the MouseEvent's button attribute

  1. If mbutton is the primary mouse button, then return 0

  2. If mbutton is the auxiliary (middle) mouse button, then return 1

  3. If mbutton is the secondary mouse button, then return 2

  4. If mbutton is the X1 (back) button, then return 3

  5. If mbutton is the X2 (forward) button, then return 4

3.4.3.9. set MouseEvent attributes from native
Input

event, the MouseEvent to initialize

native, the native mouse event

Output

None

TODO

  1. If event.type is one of [ mousedown, mouseup ], then

    1. Let mbutton be an ID from native that identifies which mouse button was pressed

    2. Set event.button = calculate MouseEvent button attribute with mbutton

3.4.3.10. handle native mouse down
Input

native, the native mousedown

Output

None

  1. Let mbutton be an ID from native that identifies which mouse button was pressed

  2. Update the mouse button bitmask as follows:

    1. If mbutton is the primary mouse button, then set the 0x01 bit

    2. If mbutton is the secondary mouse button, then set the 0x02 bit

    3. If mbutton is the auxiliary (middle) mouse button, then set the 0x04 bit

    Other buttons can be added starting with 0x08

  3. Let target = hit test with viewport-relative coordinates from native

  4. Let event = create a cancelable MouseEvent with "mousedown", target

  5. Set MouseEvent attributes from native with native

  6. Maybe send pointerdown event with event

  7. Let result = dispatch event at target

  8. If result is true and target is a focusable area that is click focusable, then

    1. Run the focusing steps at target

  9. if mbutton is the secondary mouse button, then

    1. Maybe show context menu with native, target

3.4.3.11. handle native mouse up
Input

native, the native mouseup

Output

None

Other mouse events can occur between the mousedown and mouseup.

  1. Let mbutton be an ID from native that identifies which mouse button was pressed

  2. Update the mouse button bitmask as follows:

    1. If mbutton is the primary mouse button, then clear the 0x01 bit

    2. If mbutton is the secondary mouse button, then clear the 0x02 bit

    3. If mbutton is the auxiliary (middle) mouse button, then clear the 0x04 bit

  3. Let target = hit test with viewport-relative coordinates from native

  4. Let event = create a cancelable MouseEvent with "mouseup", target

  5. Set MouseEvent attributes from native with native

  6. Maybe send pointerup event with event

  7. dispatch event at target

3.4.3.12. handle native mouse click
Input

native, the native mouse click

Output

None

The platform should call this immediately after handle native mouse up for mouseups that generate clicks.

  1. Let target = hit test with viewport-relative coordinates from native

  2. Send click event with native and target.

3.4.3.13. send click event
Input

native, the native mousedown

target, the EventTarget of the event

Output

None

  1. Let mbutton = 1 (primary mouse button by default)

  2. If native is valid, then

    1. Let mbutton be an ID from native that identifies which mouse button was pressed

  3. Set eventType = "click" if mbutton is the primary mouse button, otherwise "auxclick"

  4. Let event = create a PointerEvent with eventType and target

  5. If native is valid, then

    1. Set MouseEvent attributes from native with event, native

    2. If event.screenX is not an integer value, then round it.

    3. If event.screenY is not an integer value, then round it.

  6. dispatch event at target

See pointerevents/100 for info about browsers using PointerEvents and rounded coordinates.

Any "default action" is handled during dispatch by triggering the activation behavior algorithm for the target. So there is no need for handle that here. However, need to verify that the existing spec handles disabled/css-pointer-events/inert/...

To handle `HTMLelement.click()`, call this algorithm with native = null and target = `HTMLelement`.

To handle keyboard-initiated clicks, call this algorithm with native = null and target = currently focused element.

3.4.3.14. handle native mouse double click
Input

native, the native mouse double click

Output

None

This should be called immediately after handle native mouse click for mouse clicks that generate double clicks.

  1. Let mbutton be an ID from native that identifies which mouse button was pressed

  2. If mbutton is not the primary mouse button, then return

  3. Let target = hit test with viewport-relative coordinates from native

  4. Let event = create a PointerEvent with "dblclick" and target

  5. Set MouseEvent attributes from native with event, native

  6. If event.screenX is not an integer value, then round it.

  7. If event.screenY is not an integer value, then round it.

  8. dispatch event at target

3.4.3.15. handle native mouse move
Input

native, the native mouse move

Output

None

This algorithm makes assumptions about the dispatch of PointerEvents because they are not currently specified explicitly. Once pointerevents/285 is resolved this may need to be updated.

  1. Let target = hit test with viewport-relative coordinates from native

  2. Let targetDomPath = calculate DOM path

  3. Generate events for leaving the current element:

    1. If last mouse element is defined and not equal to target, then

      1. Let mouseout = create a cancelable MouseEvent with "mouseout" and last mouse element

      TODO: Set mouseout attributes from native. +CSSOM attributes

      1. Maybe send pointerout event with mouseout