Element: dblclick event - Web APIs

Element: dblclick event
=======================

The **`dblclick`** event fires when a pointing device button (such as a mouse's primary button) is double-clicked; that is, when it's rapidly clicked twice on a single element within a very short span of time.

`dblclick` fires after two `click` events (and by extension, after two pairs of `mousedown` and `mouseup` events).

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("dblclick", (event) => {});

ondblclick = (event) => {};
```

Event type
----------

A `MouseEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

MouseEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

Examples
--------

This example toggles the size of a card when you double click on it.

### JavaScript

```js
const card = document.querySelector("aside");

card.addEventListener("dblclick", (e) => {
  card.classList.toggle("large");
});
```

### HTML

```html
<aside>
  <h3>My Card</h3>
  <p>Double click to resize this object.</p>
</aside>
```

### CSS

```css
aside {
  background: #fe9;
  border-radius: 1em;
  display: inline-block;
  padding: 1em;
  transform: scale(0.9);
  transform-origin: 0 0;
  transition: transform 0.6s;
  user-select: none;
}

.large {
  transform: scale(1.3);
}
```

### Result

Specifications
--------------

| Specification |
| --- |
| UI Events # event-type-dblclick |
| HTML Standard # handler-ondblclick |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Introduction to events
* `auxclick`
* `click`
* `contextmenu`
* `mousedown`
* `mouseup`
* `pointerdown`
* `pointerup`


Element: insertAdjacentText() method - Web APIs

Element: insertAdjacentText() method
====================================

The **`insertAdjacentText()`** method of the `Element` interface, given a relative position and a string, inserts a new text node at the given position relative to the element it is called from.

Syntax
------

```js
insertAdjacentText(where, data)
```

### Parameters

`where`

A string representing the position relative to the element the method is called from; must be one of the following strings:

* `'beforebegin'`: Before the `element` itself.
* `'afterbegin'`: Just inside the `element`, before its first child.
* `'beforeend'`: Just inside the `element`, after its last child.
* `'afterend'`: After the `element` itself.

`data`

A string from which to create a new text node to insert at the given position `where` relative to the element the method is called from.

### Return value

None (`undefined`).

### Exceptions

`SyntaxError` `DOMException`

Thrown if `where` is not a recognized value.

### Visualization of position names

```html
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->
```

**Note:** The `beforebegin` and
 `afterend` positions work only if the node is in a tree and has an element
 parent.

Examples
--------

```js
beforeBtn.addEventListener("click", () => {
  para.insertAdjacentText("afterbegin", textInput.value);
});

afterBtn.addEventListener("click", () => {
  para.insertAdjacentText("beforeend", textInput.value);
});
```

 Have a look at our insertAdjacentText.html
 demo on GitHub (see the source code too.) Here we have a simple paragraph. You can enter some text into the form
 element, then press the *Insert before* and *Insert after* buttons to
 insert it before or after the existing paragraph text using
 `insertAdjacentText()`. Note that the existing text node is not added to —
 further text nodes are created containing the new additions.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-element-insertadjacenttext |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Element.insertAdjacentElement()`
* `Element.insertAdjacentHTML()`


Element: getAttribute() method - Web APIs

Element: getAttribute() method
==============================

 The **`getAttribute()`** method of the
 `Element` interface returns the value of a specified attribute on the
 element.

 If the given attribute does not exist, the value returned will
 either be `null` or `""` (the empty string); see Non-existing attributes for details.

Syntax
------

```js
getAttribute(attributeName)
```

### Parameters

* `attributeName` is the name of the attribute whose value you want to get.
### Return value

A string containing the value of `attributeName`.

Examples
--------

```html
<!-- example div in an HTML DOC -->
<div id="div1">Hi Champ!</div>
```

```js
// in a console
const div1 = document.getElementById("div1");
//=> <div id="div1">Hi Champ!</div>

const exampleAttr = div1.getAttribute("id");
//=> "div1"

const align = div1.getAttribute("align");
//=> null
```

Description
-----------

### Lower casing

 When called on an HTML element in a DOM flagged as an HTML document,
 `getAttribute()` lower-cases its argument before proceeding.

### Non-existing attributes

All modern web browsers return `null` when the specified attribute does not exist on the specified element.

### Retrieving nonce values

 For security reasons, CSP nonces from non-script
 sources, such as CSS selectors, and `.getAttribute("nonce")` calls are
 hidden.

```js
let nonce = script.getAttribute("nonce");
// returns empty string
```

 Instead of retrieving the nonce from the content attribute, use the
 `nonce` property:

```js
let nonce = script.nonce;
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-getattribute① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Element: keypress event - Web APIs

Element: keypress event
=======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`keypress`** event is fired when a key that produces a character value is pressed down.

Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as `Alt`, `Shift`, `Ctrl`, or `Meta`.

**Warning:** Since this event has been deprecated, you should use `beforeinput` or `keydown` instead.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("keypress", (event) => {});

onkeypress = (event) => {};
```

Event type
----------

A `KeyboardEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

KeyboardEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`KeyboardEvent.altKey` Read only

Returns a boolean value that is `true` if the `Alt` (`Option` or `⌥` on macOS) key was active when the key event was generated.

`KeyboardEvent.code` Read only

Returns a string with the code value of the physical key represented by the event.

**Warning:** This ignores the user's keyboard layout, so that if the user presses the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return "KeyY", even if the user has a QWERTZ keyboard (which would mean the user expects a "Z" and all the other properties would indicate a "Z") or a Dvorak keyboard layout (where the user would expect an "F"). If you want to display the correct keystrokes to the user, you can use `Keyboard.getLayoutMap()`.

`KeyboardEvent.ctrlKey` Read only

Returns a boolean value that is `true` if the `Ctrl` key was active when the key event was generated.

`KeyboardEvent.isComposing` Read only

Returns a boolean value that is `true` if the event is fired between after `compositionstart` and before `compositionend`.

`KeyboardEvent.key` Read only

Returns a string representing the key value of the key represented by the event.

`KeyboardEvent.location` Read only

Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown in Keyboard locations.

`KeyboardEvent.metaKey` Read only

Returns a boolean value that is `true` if the `Meta` key (on Mac keyboards, the `⌘ Command` key; on Windows keyboards, the Windows key (`⊞`)) was active when the key event was generated.

`KeyboardEvent.repeat` Read only

Returns a boolean value that is `true` if the key is being held down such that it is automatically repeating.

`KeyboardEvent.shiftKey` Read only

Returns a boolean value that is `true` if the `Shift` key was active when the key event was generated.

Examples
--------

### addEventListener keypress example

This example logs the `KeyboardEvent.code` value whenever you press a key after focussing the `<input>` element.

```html
<div>
  <label for="sample">Focus the input and type something:</label>
  <input type="text" name="text" id="sample" />
</div>
<p id="log"></p>
```

```js
const log = document.getElementById("log");
const input = document.querySelector("input");

input.addEventListener("keypress", logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}
```

### onkeypress equivalent

```js
input.onkeypress = logKey;
```

Specifications
--------------

| Specification |
| --- |
| UI Events # event-type-keypress |
| HTML Standard # handler-onkeypress |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `Document` interface, which the event also targets.
* Related events:
    + `input`
    + `keydown`
    + `keyup`


Element.ariaRowIndexText - Web APIs

Element.ariaRowIndexText
========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`ariaRowIndexText`** property of the `Element` interface reflects the value of the `aria-rowindextext` attribute, which defines a human readable text alternative of aria-rowindex.

Value
-----

A string.

Examples
--------

In this example the `aria-rowindextext` attribute on the element with an ID of `role-heading` is set to "Heading row". Using `ariaRowIndexText` we update the value to "Updated heading row".

```html
<table
 id="semantic-table"
 role="table"
 aria-label="Semantic Elements"
 aria-describedby="semantic\_elements\_table\_desc"
 aria-rowcount="100">
  <caption id="semantic\_elements\_table\_desc">
    Semantic Elements to use instead of ARIA's roles
  </caption>
  <thead role="rowgroup">
    <tr role="row">
      <th
 role="columnheader"
 id="role-heading"
 aria-sort="none"
 aria-rowindex="1"
 aria-rowindextext="Heading row">
        ARIA Role
      </th>
      <th
 role="columnheader"
 id="element-heading"
 aria-sort="none"
 aria-rowindex="1">
        Semantic Element
      </th>
    </tr>
  </thead>
  <tbody role="rowgroup">
    <tr role="row">
      <td role="cell" aria-rowindex="11">header</td>
      <td role="cell" aria-rowindex="11">h1</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="16">header</td>
      <td role="cell" aria-rowindex="16">h6</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="18">rowgroup</td>
      <td role="cell" aria-rowindex="18">thead</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="24">term</td>
      <td role="cell" aria-rowindex="24">dt</td>
    </tr>
  </tbody>
</table>
```

```js
let el = document.getElementById("role-heading");
console.log(el.ariaRowIndexText); // "Heading row"
el.ariaRowIndexText = "Updated heading row";
console.log(el.ariaRowIndexText); // "Updated heading row"
```

Specifications
--------------

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariarowindextext |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ARIA: table role


Element: mousedown event - Web APIs

Element: mousedown event
========================

The **`mousedown`** event is fired at an `Element` when a pointing device button is pressed while the pointer is inside the element.

**Note:** This differs from the `click` event in that `click` is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. `mousedown` is fired the moment the button is initially pressed.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("mousedown", (event) => {});

onmousedown = (event) => {};
```

Event type
----------

A `MouseEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

MouseEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

Examples
--------

See `mousemove` event for example code.

Specifications
--------------

| Specification |
| --- |
| UI Events # event-type-mousedown |
| HTML Standard # handler-onmousedown |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Introduction to events
* `mouseup`
* `mousemove`
* `click`
* `dblclick`
* `mouseover`
* `mouseout`
* `mouseenter`
* `mouseleave`
* `contextmenu`


Element: securitypolicyviolation event - Web APIs

Element: securitypolicyviolation event
======================================

The **`securitypolicyviolation`** event is fired when a Content Security Policy is violated.

 The event is fired on the element that violates the policy and bubbles.
 It is normally handled by an event handler on the `Window` or `Document` object.

The handler can be assigned using the `onsecuritypolicyviolation` property or using `EventTarget.addEventListener()`.

**Note:** You must add the handler for this event to a top level object (i.e. `Window` or `Document`).
 While the property exists in HTML elements, you can't assign a handler to the property until the elements have been loaded, by which time this event will already have fired.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("securitypolicyviolation", (event) => {});

onsecuritypolicyviolation = (event) => {};
```

Event type
----------

A `SecurityPolicyViolationEvent`. Inherits from `Event`.

Event

SecurityPolicyViolationEventExamples
--------

The code below shows how you might add an event handler function using the `onsecuritypolicyviolation` global event handler property or `addEventListener()` on the top level `Window` (you could use exactly the same approach on `Document`).

```js
window.onsecuritypolicyviolation = (e) => {
  // Handle SecurityPolicyViolationEvent e here
};

window.addEventListener("securitypolicyviolation", (e) => {
  // Handle SecurityPolicyViolationEvent e here
});
```

Specifications
--------------

| Specification |
| --- |
| Content Security Policy Level 3 # eventdef-globaleventhandlers-securitypolicyviolation |
| HTML Standard # handler-onsecuritypolicyviolation |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `securitypolicyviolation` event of the `Document` interface
* The `securitypolicyviolation` event of the `WorkerGlobalScope` interface
* HTTP > Content Security Policy


Element: ariaPosInSet property - Web APIs

Element: ariaPosInSet property
==============================

The **`ariaPosInSet`** property of the `Element` interface reflects the value of the `aria-posinset` attribute, which defines an element's number or position in the current set of listitems or treeitems.

Value
-----

A string containing an integer.

Examples
--------

In this example the `aria-posinset` attribute on the element with an ID of `article2` is set to "2". Using `ariaPosInSet` we update the value to "3".

```html
<article id="article1" aria-posinset="1">…</article>
<article id="article2" aria-posinset="2">…</article>
```

```js
let el = document.getElementById("article2");
console.log(el.ariaPosInSet); // "2"
el.ariaPosInSet = "3";
console.log(el.ariaPosInSet); // "3"
```

Specifications
--------------

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariaposinset |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Element: scroll event - Web APIs

Element: scroll event
=====================

 The **`scroll`** event fires when an element has been scrolled.
 To detect when scrolling has completed, see the `Element: scrollend event`.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("scroll", (event) => {});

onscroll = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

 The following examples show how to use the `scroll` event with an event listener and with the `onscroll` event handler property.
 The `setTimeout()` method is used to throttle the event handler because `scroll` events can fire at a high rate.
 For additional examples that use `requestAnimationFrame()`, see the `Document: scroll event` page.

### Using `scroll` with an event listener

The following example shows how to use the `scroll` event to detect when the user is scrolling inside an element:

```html
<div
 id="scroll-box"
 style="overflow: scroll; height: 100px; width: 100px; float: left;">
  <p style="height: 200px; width: 200px;">Scroll me!</p>
</div>
<p style="text-align: center;" id="output">Waiting on scroll events...</p>
```

```js
const element = document.querySelector("div#scroll-box");
const output = document.querySelector("p#output");

element.addEventListener("scroll", (event) => {
  output.innerHTML = "Scroll event fired!";
  setTimeout(() => {
    output.innerHTML = "Waiting on scroll events...";
  }, 1000);
});
```

### Using `onscroll` event handler property

The following example shows how to use the `onscroll` event handler property to detect when the user is scrolling:

```html
<div
 id="scroll-box"
 style="overflow: scroll; height: 100px; width: 100px; float: left;">
  <p style="height: 200px; width: 200px;">Scroll me!</p>
</div>
<p id="output" style="text-align: center;">Waiting on scroll events...</p>
```

```js
const element = document.querySelector("div#scroll-box");
const output = document.querySelector("p#output");

element.onscroll = (event) => {
  output.innerHTML = "Element scroll event fired!";
  setTimeout(() => {
    output.innerHTML = "Waiting on scroll events...";
  }, 1000);
};
```

Specifications
--------------

| Specification |
| --- |
| CSSOM View Module # eventdef-document-scroll |
| HTML Standard # handler-onscroll |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Element `scrollend` event
* Document `scroll` event
* Document `scrollend` event


Element: removeAttribute() method - Web APIs

Element: removeAttribute() method
=================================

 The `Element` method
 **`removeAttribute()`** removes the attribute with the
 specified name from the element.

Syntax
------

```js
removeAttribute(attrName)
```

### Parameters

`attrName`

 A string specifying the name of the attribute to remove from the
 element. If the specified attribute does not exist, `removeAttribute()`
 returns without generating an error.

### Return value

None (`undefined`).

Usage notes
-----------

 You should use `removeAttribute()` instead of setting the attribute value to
 `null` either directly or using `setAttribute()`. Many attributes will not behave as expected if you set them to
 `null`.

DOM methods dealing with element's attributes:

| Not namespace-aware, most commonly used methods | Namespace-aware variants (DOM Level 2) | DOM Level 1 methods for dealing with `Attr` nodes directly (seldom used) | DOM Level 2 namespace-aware methods for dealing with `Attr` nodes directly (seldom used) |
| --- | --- | --- | --- |
| `setAttribute` (DOM 1) | `setAttributeNS` | `setAttributeNode` | `setAttributeNodeNS` |
| `getAttribute` (DOM 1) | `getAttributeNS` | `getAttributeNode` | `getAttributeNodeNS` |
| `hasAttribute` (DOM 2) | `hasAttributeNS` | - | - |
| `removeAttribute` (DOM 1) | `removeAttributeNS` | `removeAttributeNode` | - |

Examples
--------

```js
// Given: <div id="div1" disabled width="200px">
document.getElementById("div1").removeAttribute("disabled");
// Now: <div id="div1" width="200px">
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-removeattribute① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Element: scrollTop property - Web APIs

Element: scrollTop property
===========================

The **`Element.scrollTop`** property gets or sets the number of pixels that an element's content is scrolled vertically.

An element's `scrollTop` value is a measurement of the distance from the element's top to its topmost *visible* content. When an element's content does not generate a vertical scrollbar, then its `scrollTop` value is `0`.

`scrollTop` can be set to any integer value, with certain caveats:

* If the element can't be scrolled (e.g. it has no overflow or if the element has a property of "**non-scrollable**"), `scrollTop` is `0`.
* `scrollTop` doesn't respond to negative values; instead, it sets itself back to `0`.
* If set to a value greater than the maximum available for the element, `scrollTop` settles itself to the maximum value.

When `scrollTop` is used on the root element (the `<html>` element), the `scrollY` of the window is returned. This is a special case of `scrollTop`.

**Warning:** On systems using display scaling, `scrollTop` may give you a decimal value.

Value
-----

A number.

Examples
--------

### Scrolling an element

In this example, try scrolling the inner container with the dashed border, and see how the value of `scrollTop` changes.

#### HTML

```html
<div id="container">
  <div id="scroller">
    <p>
      Far out in the uncharted backwaters of the unfashionable end of the
      western spiral arm of the Galaxy lies a small unregarded yellow sun.
      Orbiting this at a distance of roughly ninety-two million miles is an
      utterly insignificant little blue green planet whose ape-descended life
      forms are so amazingly primitive that they still think digital watches are
      a pretty neat idea.
    </p>
  </div>
</div>

<div id="output">scrollTop: 0</div>
```

#### CSS

```css
#scroller {
  overflow: scroll;
  height: 150px;
  width: 150px;
  border: 5px dashed orange;
}

#output {
  padding: 1rem 0;
}
```

#### JavaScript

```js
const scroller = document.querySelector("#scroller");
const output = document.querySelector("#output");

scroller.addEventListener("scroll", (event) => {
  output.textContent = `scrollTop: ${scroller.scrollTop}`;
});
```

#### Result

Specifications
--------------

| Specification |
| --- |
| CSSOM View Module # dom-element-scrolltop |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* MSDN's Measuring Element Dimension and Location
* `Element.scrollLeft`
* `Element.scrollTo()`


Element: requestPointerLock() method - Web APIs

Element: requestPointerLock() method
====================================

The **`requestPointerLock()`** method of the `Element` interface lets you asynchronously ask for the pointer to be locked on the given element.

To track the success or failure of the request, it is necessary to listen for the `pointerlockchange` and `pointerlockerror` events at the `Document` level.

**Note:** In the current specification, `requestPointerLock()` only communicates the success or failure of the request by firing `pointerlockchange` or `pointerlockerror` events. A proposed update to the specification updates `requestPointerLock()` to return a `Promise` which communicates success or failure. This page documents the version that returns a `Promise`. However, note that this version is not yet a standard and is not implemented by all browsers. See Browser compatibility for more information.

Syntax
------

```js
requestPointerLock()
requestPointerLock(options)
```

### Parameters

`options` Optional

An options object that can contain the following properties:

`unadjustedMovement` Optional

Disables OS-level adjustment for mouse acceleration, and accesses raw mouse input instead. The default value is `false`; setting it to `true` will disable mouse acceleration.

### Return value

A `Promise` that resolves with `undefined`.

Security
--------

Transient activation is required when calling `requestPointerLock()`. The user has to interact with the page or a UI element in order for this feature to work. Also, the target element's associated document must be in the active state.

If calling `requestPointerLock()` immediately after releasing the pointer lock via the default unlock gesture (instead of through a `exitPointerLock()` call), the call will fail, even if a transient activation is available.

If calling `requestPointerLock()` with `requestFullscreen()`, the `requestPointerLock()` must be called first, because the `requestFullscreen()` will consume the state of transient activation.

The `allow-pointer-lock` sandbox token must be added when calling `requestPointerLock()` in an `<iframe>` element. Also, no other elements in other `<iframe>` elements may be in pointer lock mode.

Examples
--------

Pointer lock is often used in online games, when you want your mouse movement to be focused on controlling the game, without the distraction of the mouse pointer moving around, going outside the game area, or reaching the edge of the window.

To enable pointer lock, you would get the user to interact with the UI in some way, perhaps by pressing a button, or the game canvas itself.

```js
canvas.addEventListener("click", async () => {
  await canvas.requestPointerLock();
});
```

Operating systems enable mouse acceleration by default, which is useful when you sometimes want slow precise movement (think about you might use a graphics package), but also want to move great distances with a faster mouse movement (think about scrolling, and selecting several files). For some first-person perspective games however, raw mouse input data is preferred for controlling camera rotation — where the same distance movement, fast or slow, results in the same rotation. This results in a better gaming experience and higher accuracy, according to professional gamers.

To disable OS-level mouse acceleration and access raw mouse input, you can set the `unadjustedMovement` to `true`:

```js
canvas.addEventListener("click", async () => {
  await canvas.requestPointerLock({
    unadjustedMovement: true,
  });
});
```

For more example code, see:

* pointer lock demo (see source code)
* Pointer Lock API
* Disable mouse acceleration to provide a better FPS gaming experience
Specifications
--------------

| Specification |
| --- |
| Pointer Lock 2.0 # dom-element-requestpointerlock |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Document.pointerLockElement`
* `Document.exitPointerLock()`
* Pointer Lock


Element: removeAttributeNS() method - Web APIs

Element: removeAttributeNS() method
===================================

 The **`removeAttributeNS()`** method of the
 `Element` interface removes the specified attribute from an element.

Syntax
------

```js
removeAttributeNS(namespace, attrName)
```

### Parameters

* `namespace` is a string that contains the namespace of the attribute.
* `attrName` is a string that names the attribute to be removed from the
 current node.
### Return value

None (`undefined`).

Examples
--------

```js
// Given:
// <div id="div1" xmlns:special="http://www.mozilla.org/ns/specialspace"
// special:specialAlign="utterleft" width="200px" />
d = document.getElementById("div1");
d.removeAttributeNS("http://www.mozilla.org/ns/specialspace", "specialAlign");
// Now: <div id="div1" width="200px" />
```

Notes
-----

DOM methods dealing with element's attributes:

| Not namespace-aware, most commonly used methods | Namespace-aware variants (DOM Level 2) | DOM Level 1 methods for dealing with `Attr` nodes directly (seldom used) | DOM Level 2 namespace-aware methods for dealing with `Attr` nodes directly (seldom used) |
| --- | --- | --- | --- |
| `setAttribute` (DOM 1) | `setAttributeNS` | `setAttributeNode` | `setAttributeNodeNS` |
| `getAttribute` (DOM 1) | `getAttributeNS` | `getAttributeNode` | `getAttributeNodeNS` |
| `hasAttribute` (DOM 2) | `hasAttributeNS` | - | - |
| `removeAttribute` (DOM 1) | `removeAttributeNS` | `removeAttributeNode` | - |

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-removeattributens① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

 In Firefox 3 and later, this method resets DOM values to
 their defaults.


Element: ariaChecked property - Web APIs

Element: ariaChecked property
=============================

The **`ariaChecked`** property of the `Element` interface reflects the value of the `aria-checked` attribute, which indicates the current "checked" state of checkboxes, radio buttons, and other widgets that have a checked state.

**Note:** Where possible use an HTML `<input>` element with `type="checkbox"` as this element has built in semantics and does not require ARIA attributes.

Value
-----

A string with one of the following values:

`"true"`

The element is checked.

`"mixed"`

Indicates a mixed mode value for a tri-state checkbox or menuitemcheckbox.

`"false"`

The element supports being checked but is not currently checked.

`"undefined"`

The element does not support being checked.

Examples
--------

In this example the `aria-checked` attribute on the element with an ID of `checkBoxInput` is set to "false" indicating that this input is currently unchecked. Using `ariaChecked` we update the value to "true".

```html
<span
 role="checkbox"
 id="checkBoxInput"
 aria-checked="false"
 tabindex="0"
 aria-labelledby="chk1-label">
</span>
<label id="chk1-label">Remember my preferences</label>
```

```js
let el = document.getElementById("checkBoxInput");
console.log(el.ariaChecked); // "false"
el.ariaChecked = "true";
console.log(el.ariaChecked); // "true"
```

Specifications
--------------

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariachecked |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ARIA: checkbox role


Element: setCapture() method - Web APIs

Element: setCapture() method
============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 Call this method during the handling of a mousedown event to retarget all mouse events
 to this element until the mouse button is released or `document.releaseCapture()` is called.

**Warning:** This interface never had much cross-browser
 support and you probably looking for `element.setPointerCapture` instead,
 from the Pointer Events API.

Syntax
------

```js
setCapture(retargetToElement)
```

### Parameters

`retargetToElement`

 If `true`, all events are targeted directly to this element; if
 `false`, events can also fire at descendants of this element.

### Return value

None (`undefined`).

Examples
--------

 In this example, the current mouse coordinates are drawn while you mouse around after
 clicking and holding down on an element.

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Mouse Capture Example</title>
    <style>
 #myButton {
 border: solid black 1px;
 color: black;
 padding: 2px;
 box-shadow: black 2px 2px;
 }
 </style>

    <script>
 function init() {
 const btn = document.getElementById("myButton");
 if (btn.setCapture) {
 btn.addEventListener("mousedown", mouseDown, false);
 btn.addEventListener("mouseup", mouseUp, false);
 } else {
 document.getElementById("output").textContent =
 "Sorry, there appears to be no setCapture support on this browser";
 }
 }

 function mouseDown(e) {
 e.target.setCapture();
 e.target.addEventListener("mousemove", mouseMoved, false);
 }

 function mouseUp(e) {
 e.target.removeEventListener("mousemove", mouseMoved, false);
 }

 function mouseMoved(e) {
 const output = document.getElementById("output");
 output.textContent = `Position: ${e.clientX}, ${e.clientY}`;
 }
 </script>
  </head>
  <body onload="init()">
    <p>
      This is an example of how to use mouse capture on elements in Gecko 2.0.
    </p>
    <p><a id="myButton" href="#">Test Me</a></p>
    <div id="output">No events yet</div>
  </body>
</html>
```

View Live Examples

Notes
-----

 The element may not be scrolled completely to the top or bottom, depending on the
 layout of other elements.

Specifications
--------------

Not part of any specification.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `document.releaseCapture()`
* `element.setPointerCapture`


Element: ariaMultiLine property - Web APIs

Element: ariaMultiLine property
===============================

The **`ariaMultiLine`** property of the `Element` interface reflects the value of the `aria-multiline` attribute, which indicates whether a text box accepts multiple lines of input or only a single line.

**Note:** Where possible use an HTML `<input>` element with `type="text"` or a `<textarea>` as these have built in semantics and do not require ARIA attributes.

Value
-----

A string with one of the following values:

`"true"`

This is a multi-line text box.

`"false"`

This is a single-line text box.

Examples
--------

In this example the `aria-multiline` attribute on the element with an ID of `txtBoxInput` is set to "true" indicating that this box allows for multiple lines of input. Using `ariaMultiLine` we update the value to "false".

```html
<div id="txtboxMultilineLabel">Enter the tags for the article</div>
<div
 role="textbox"
 id="txtBoxInput"
 contenteditable="true"
 aria-multiline="true"
 aria-labelledby="txtboxMultilineLabel"
 aria-required="true"></div>
```

```js
let el = document.getElementById("txtBoxInput");
console.log(el.ariaMultiLine); // "true"
el.ariaMultiLine = "false";
console.log(el.ariaMultiLine); // "false"
```

Specifications
--------------

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariamultiline |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ARIA: textbox role


Element: pointercancel event - Web APIs

Element: pointercancel event
============================

The **`pointercancel`** event is fired when the browser determines that there are unlikely to be any more pointer events, or if after the `pointerdown` event is fired, the pointer is then used to manipulate the viewport by panning, zooming, or scrolling.

Some examples of situations that will trigger a `pointercancel` event:

* A hardware event occurs that cancels the pointer activities. This may include, for example, the user switching applications using an application switcher interface or the "home" button on a mobile device.
* The device's screen orientation is changed while the pointer is active.
* The browser decides that the user started pointer input accidentally. This can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events.
* The `touch-action` CSS property prevents the input from continuing.
* When the user interacts with too many simultaneous pointers, the browser can fire this event for all existing pointers (even if the user is still touching the screen).

**Note:** After the `pointercancel` event is fired, the browser will also send `pointerout` followed by `pointerleave`.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("pointercancel", (event) => {});

onpointercancel = (event) => {};
```

Event type
----------

A `PointerEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

PointerEventEvent properties
----------------

*This interface inherits properties from `MouseEvent` and `Event`.*

`PointerEvent.altitudeAngle` Read only
Experimental

Represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen.

`PointerEvent.azimuthAngle` Read only
Experimental

Represents the angle between the Y-Z plane and the plane containing both the transducer (a pointer or stylus) axis and the Y axis.

`PointerEvent.pointerId` Read only

A unique identifier for the pointer causing the event.

`PointerEvent.width` Read only

The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.height` Read only

The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.pressure` Read only

The normalized pressure of the pointer input in the range `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

`PointerEvent.tangentialPressure` Read only

The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control.

`PointerEvent.tiltX` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

`PointerEvent.tiltY` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

`PointerEvent.twist` Read only

The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

`PointerEvent.pointerType` Read only

Indicates the device type that caused the event (mouse, pen, touch, etc.).

`PointerEvent.isPrimary` Read only

Indicates if the pointer represents the primary pointer of this pointer type.

Examples
--------

Using `addEventListener()`:

```js
const para = document.querySelector("p");

para.addEventListener("pointercancel", (event) => {
  console.log("Pointer event cancelled");
});
```

Using the `onpointercancel` event handler property:

```js
const para = document.querySelector("p");

para.onpointercancel = (event) => {
  console.log("Pointer event cancelled");
};
```

Specifications
--------------

| Specification |
| --- |
| Pointer Events # the-pointercancel-event |
| Pointer Events # dom-globaleventhandlers-onpointercancel |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Related events
    + `gotpointercapture`
    + `lostpointercapture`
    + `pointerover`
    + `pointerenter`
    + `pointerdown`
    + `pointermove`
    + `pointerup`
    + `pointercancel`
    + `pointerout`
    + `pointerleave`
    + `pointerrawupdate`


Element: scrollTopMax property - Web APIs

Element: scrollTopMax property
==============================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`Element.scrollTopMax`** read-only property returns a
 number representing the maximum top scroll offset possible for the
 element.

Value
-----

A number.

Specifications
--------------

*This property is not part of any specification.*

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Element.scrollLeftMax` giving the same information for the other axis.


Element: pointerout event - Web APIs

Element: pointerout event
=========================

The `pointerout` event is fired for several reasons including: pointing device is moved out of the *hit test* boundaries of an element; firing the `pointerup` event for a device that does not support hover (see `pointerup`); after firing the `pointercancel` event (see `pointercancel`); when a pen stylus leaves the hover range detectable by the digitizer.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("pointerout", (event) => {});

onpointerout = (event) => {};
```

Event type
----------

A `PointerEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

PointerEventEvent properties
----------------

*This interface inherits properties from `MouseEvent` and `Event`.*

`PointerEvent.altitudeAngle` Read only
Experimental

Represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen.

`PointerEvent.azimuthAngle` Read only
Experimental

Represents the angle between the Y-Z plane and the plane containing both the transducer (a pointer or stylus) axis and the Y axis.

`PointerEvent.pointerId` Read only

A unique identifier for the pointer causing the event.

`PointerEvent.width` Read only

The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.height` Read only

The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.pressure` Read only

The normalized pressure of the pointer input in the range `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

`PointerEvent.tangentialPressure` Read only

The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control.

`PointerEvent.tiltX` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

`PointerEvent.tiltY` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

`PointerEvent.twist` Read only

The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

`PointerEvent.pointerType` Read only

Indicates the device type that caused the event (mouse, pen, touch, etc.).

`PointerEvent.isPrimary` Read only

Indicates if the pointer represents the primary pointer of this pointer type.

Examples
--------

Using `addEventListener()`:

```js
const para = document.querySelector("p");

para.addEventListener("pointerout", (event) => {
  console.log("Pointer moved out");
});
```

Using the `onpointerout` event handler property:

```js
const para = document.querySelector("p");

para.onpointerout = (event) => {
  console.log("Pointer moved out");
};
```

Specifications
--------------

| Specification |
| --- |
| Pointer Events # the-pointerout-event |
| Pointer Events # dom-globaleventhandlers-onpointerout |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Related events
    + `gotpointercapture`
    + `lostpointercapture`
    + `pointerover`
    + `pointerenter`
    + `pointerdown`
    + `pointermove`
    + `pointerup`
    + `pointercancel`
    + `pointerout`
    + `pointerleave`
    + `pointerrawupdate`


Element: getAttributeNode() method - Web APIs

Element: getAttributeNode() method
==================================

Returns the specified attribute of the specified element, as an `Attr` node.

Syntax
------

```js
getAttributeNode(attrName)
```

### Parameters

* `attrName` is a string containing the name of the attribute.
### Return value

An `Attr` node for the attribute.

Examples
--------

```js
// html: <div id="top" />
let t = document.getElementById("top");
let idAttr = t.getAttributeNode("id");
alert(idAttr.value === "top");
```

Notes
-----

When called on an HTML element in a DOM flagged as an HTML document, `getAttributeNode` lower-cases its argument before proceeding.

The `Attr` node inherits from `Node`, but is not considered a part of the document tree. Common `Node` attributes like parentNode, previousSibling, and nextSibling are `null` for an `Attr` node. You can, however, get the element to which the attribute belongs with the `ownerElement` property.

getAttribute is usually used instead of `getAttributeNode` to get the value of an element's attribute.

DOM methods dealing with element's attributes:

| Not namespace-aware, most commonly used methods | Namespace-aware variants (DOM Level 2) | DOM Level 1 methods for dealing with `Attr` nodes directly (seldom used) | DOM Level 2 namespace-aware methods for dealing with `Attr` nodes directly (seldom used) |
| --- | --- | --- | --- |
| `setAttribute` (DOM 1) | `setAttributeNS` | `setAttributeNode` | `setAttributeNodeNS` |
| `getAttribute` (DOM 1) | `getAttributeNS` | `getAttributeNode` | `getAttributeNodeNS` |
| `hasAttribute` (DOM 2) | `hasAttributeNS` | - | - |
| `removeAttribute` (DOM 1) | `removeAttributeNS` | `removeAttributeNode` | - |

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-element-getattributenode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Element: before() method - Web APIs

Element: before() method
========================

 The **`Element.before()`** method inserts a set of
 `Node` or string objects in the children list of this
 `Element`'s parent, just before this `Element`.
 String objects are inserted as equivalent `Text` nodes.

Syntax
------

```js
before(param1)
before(param1, param2)
before(param1, param2, /\* …, \*/ paramN)
```

### Parameters

`param1`, …, `paramN`

A set of `Node` or string objects to insert.

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

Thrown when the node cannot be inserted at the specified point in the hierarchy.

Examples
--------

### Inserting an element

```js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.before(span);

console.log(container.outerHTML);
// "<div><span></span><p></p></div>"
```

### Inserting text

```js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);

p.before("Text");

console.log(container.outerHTML);
// "<div>Text<p></p></div>"
```

### Inserting an element and text

```js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.before(span, "Text");

console.log(container.outerHTML);
// "<div><span></span>Text<p></p></div>"
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-childnode-before① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Element.after()`
* `Element.append()`
* `Node.appendChild()`
* `Node.insertBefore()`
* `Element.insertAdjacentElement()`
* `NodeList`


Element: transitionstart event - Web APIs

Element: transitionstart event
==============================

The **`transitionstart`** event is fired when a CSS transition has actually started, i.e., after any `transition-delay` has ended.

This event is not cancelable.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("transitionstart", (event) => {});

ontransitionstart = (event) => {};
```

Event type
----------

A `TransitionEvent`. Inherits from `Event`.

Event

TransitionEventEvent properties
----------------

*Also inherits properties from its parent `Event`*.

`TransitionEvent.propertyName` Read only

A string containing the name CSS property associated with the transition.

`TransitionEvent.elapsedTime` Read only

A `float` giving the amount of time the transition has been running, in seconds, when this event fired. This value is not affected by the `transition-delay` property.

`TransitionEvent.pseudoElement` Read only

A string, starting with `::`, containing the name of the pseudo-element the animation runs on. If the transition doesn't run on a pseudo-element but on the element, an empty string: `''`.

Examples
--------

This code adds a listener to the `transitionstart` event:

```js
element.addEventListener("transitionstart", () => {
  console.log("Started transitioning");
});
```

The same, but using the `ontransitionstart` property instead of `addEventListener()`:

```js
element.ontransitionstart = () => {
  console.log("Started transitioning");
};
```

### Live example

In the following example, we have a simple `<div>` element, styled with a transition that includes a delay:

```html
<div class="transition">Hover over me</div>
<div class="message"></div>
```

```css
.transition {
  width: 100px;
  height: 100px;
  background: rgb(255 0 0 / 100%);
  transition-property: transform, background;
  transition-duration: 2s;
  transition-delay: 1s;
}

.transition:hover {
  transform: rotate(90deg);
  background: rgb(255 0 0 / 0%);
}
```

To this, we'll add some JavaScript to indicate where the `transitionstart` and `transitionrun` events fire.

```js
const transition = document.querySelector(".transition");
const message = document.querySelector(".message");

transition.addEventListener("transitionrun", () => {
  message.textContent = "transitionrun fired";
});

transition.addEventListener("transitionstart", () => {
  message.textContent = "transitionstart fired";
});

transition.addEventListener("transitionend", () => {
  message.textContent = "transitionend fired";
});
```

The difference is that:

* transitionrun fires when the transition is created (i.e. at the start of any delay).
* transitionstart fires when the actual animation has begun (i.e. at the end of any delay).
Specifications
--------------

| Specification |
| --- |
| CSS Transitions # transitionstart |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TransitionEvent` interface
* CSS properties: `transition`, `transition-delay`, `transition-duration`, `transition-property`, `transition-timing-function`
* Related events: `transitionend`, `transitionrun`, `transitioncancel`


Element: after() method - Web APIs

Element: after() method
=======================

 The **`Element.after()`** method inserts a set of
 `Node` or string objects in the children list of the
 `Element`'s parent, just after the `Element`.
 String objects are inserted as equivalent `Text` nodes.

Syntax
------

```js
after(node1)
after(node1, node2)
after(node1, node2, /\* …, \*/ nodeN)
```

### Parameters

`node1`, …, `nodeN`

A set of `Node` or string objects to insert.

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

Thrown when the node cannot be inserted at the specified point in the hierarchy.

Examples
--------

### Inserting an element

```js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.after(span);

console.log(container.outerHTML);
// "<div><p></p><span></span></div>"
```

### Inserting text

```js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);

p.after("Text");

console.log(container.outerHTML);
// "<div><p></p>Text</div>"
```

### Inserting an element and text

```js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.after(span, "Text");

console.log(container.outerHTML);
// "<div><p></p><span></span>Text</div>"
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-childnode-after① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Element.before()`
* `Element.append()`
* `Node.appendChild()`
* `Element.insertAdjacentElement()`
* `NodeList`


Element: ariaColIndex property - Web APIs

Element: ariaColIndex property
==============================

The **`ariaColIndex`** property of the `Element` interface reflects the value of the `aria-colindex` attribute, which defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.

Value
-----

A string which contains an integer.

Examples
--------

In this example the `aria-colindex` attribute on the element with an ID of `role-heading` is set to "1". Using `ariaColIndex` we update the value to "2".

```html
<table
 id="semantic-table"
 role="table"
 aria-label="Semantic Elements"
 aria-describedby="semantic\_elements\_table\_desc"
 aria-rowcount="100">
  <caption id="semantic\_elements\_table\_desc">
    Semantic Elements to use instead of ARIA's roles
  </caption>
  <thead role="rowgroup">
    <tr role="row">
      <th
 role="columnheader"
 id="role-heading"
 aria-sort="none"
 aria-rowindex="1"
 aria-colindex="1">
        ARIA Role
      </th>
      <th
 role="columnheader"
 id="element-heading"
 aria-sort="none"
 aria-rowindex="1">
        Semantic Element
      </th>
    </tr>
  </thead>
  <tbody role="rowgroup">
    <tr role="row">
      <td role="cell" aria-rowindex="11">header</td>
      <td role="cell" aria-rowindex="11">h1</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="16">header</td>
      <td role="cell" aria-rowindex="16">h6</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="18">rowgroup</td>
      <td role="cell" aria-rowindex="18">thead</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="24">term</td>
      <td role="cell" aria-rowindex="24">dt</td>
    </tr>
  </tbody>
</table>
```

```js
let el = document.getElementById("role-heading");
console.log(el.ariaColIndex); // 1
el.ariaColIndex = "2";
console.log(el.ariaColIndex); // 2
```

Specifications
--------------

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariacolindex |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ARIA: table role


Element: innerHTML property - Web APIs

Element: innerHTML property
===========================

 The `Element` property
 **`innerHTML`** gets or sets the HTML or XML markup contained
 within the element.

 To insert the HTML into the document rather than replace the contents of an element,
 use the method `insertAdjacentHTML()`.

Value
-----

 A string containing the HTML serialization of the element's
 descendants. Setting the value of `innerHTML` removes all of the element's
 descendants and replaces them with nodes constructed by parsing the HTML given in the
 string *htmlString*.

### Exceptions

`SyntaxError` `DOMException`

 Thrown if an attempt was made to set the value of `innerHTML` using a string which
 is not properly-formed HTML.

`NoModificationAllowedError` `DOMException`

 Thrown if an attempt was made to insert the HTML into a node whose parent is a
 `Document`.

Usage notes
-----------

The `innerHTML` property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.

### Reading the HTML contents of an element

Reading `innerHTML` causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned.

```js
let contents = myElement.innerHTML;
```

This lets you look at the HTML markup of the element's content nodes.

**Note:** The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment
 is likely not to match the original page markup.

### Replacing the contents of an element

Setting the value of `innerHTML` lets you easily replace the existing contents of an element with new content.

**Note:** This is a security risk if the string to be inserted might contain potentially malicious content.
 When inserting user-supplied data you should always consider using `Element.setHTML()` instead, in order to sanitize the content before it is inserted.

For example, you can erase the entire contents of a document by clearing the contents of the document's `body` attribute:

```js
document.body.innerHTML = "";
```

 This example fetches the document's current HTML markup and replaces the `"<"` characters with the HTML entity `"<"`, thereby essentially converting the HTML into raw text.
 This is then wrapped in a `<pre>` element.
 Then the value of `innerHTML` is changed to this new string.
 As a result, the document contents are replaced with a display of the page's entire source code.

```js
document.documentElement.innerHTML = `<pre>${document.documentElement.innerHTML.replace(
 /</g,
 "<",
)}</pre>`;
```

#### Operational details

 What exactly happens when you set value of `innerHTML`?
 Doing so causes the user agent to follow these steps:

1. The specified value is parsed as HTML or XML (based on the document type),
 resulting in a `DocumentFragment` object representing the new set of DOM nodes for the new elements.
2. If the element whose contents are being replaced is a `<template>` element,
 then the `<template>` element's `content` attribute is replaced with the new `DocumentFragment` created in step 1.
3. For all other elements, the element's contents are replaced with the nodes in the new `DocumentFragment`.
### Appending HTML to an element

Setting the value of `innerHTML` lets you append new contents to the existing one of an element.

For example, we can append a new list item (`<li>`) to the existing list (`<ul>`):

#### HTML

```html
<ul id="list">
  <li><a href="#">Item 1</a></li>
  <li><a href="#">Item 2</a></li>
  <li><a href="#">Item 3</a></li>
</ul>
```

#### JavaScript

```js
const list = document.getElementById("list");

list.innerHTML += `<li><a href="#">Item ${list.children.length + 1}</a></li>`;
```

 Please note that using `innerHTML` to append HTML elements (e.g. `el.innerHTML += "<a href='…'>link</a>"`) will result in the removal of any previously set event listeners.
 That is, after you append any HTML element that way you won't be able to listen to the previously set event listeners.

### Security considerations

 It is not uncommon to see `innerHTML` used to insert text into a web page.
 There is potential for this to become an attack vector on a site, creating a potential security risk.

```js
let name = "John";
// assuming 'el' is an HTML DOM element
el.innerHTML = name; // harmless in this case

// …

name = "<script>alert('I am John in an annoying alert!')</script>";
el.innerHTML = name; // harmless in this case
```

 Although this may look like a cross-site scripting
 attack, the result is harmless. HTML specifies that a `<script>` tag
 inserted with `innerHTML` should not execute.

 However, there are ways to execute JavaScript without using `<script>` elements,
 so there is still a security risk whenever you use `innerHTML` to set strings over which you have no control.
 For example:

```js
const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert
```

For that reason, it is recommended that instead of `innerHTML` you use:

* `Element.setHTML()` to sanitize the text before it is inserted into the DOM.
* `Node.textContent` when inserting plain text, as this inserts it as raw text rather than parsing it as HTML.

**Warning:** If your project is one that will undergo any form of security review, using `innerHTML` most likely will result in your code being rejected.
 For example, if you use `innerHTML` in a browser extension and submit
 the extension to addons.mozilla.org, it may be rejected in the review process.
 Please see Safely inserting external content into a page for alternative methods.

Examples
--------

This example uses `innerHTML` to create a mechanism for logging messages into a box on a web page.

### JavaScript

```js
function log(msg) {
  const logElem = document.querySelector(".log");

  const time = new Date();
  const timeStr = time.toLocaleTimeString();
  logElem.innerHTML += `${timeStr}: ${msg}<br/>`;
}

log("Logging mouse events inside this container…");
```

 The `log()` function creates the log output by getting the current time from a `Date` object using
 `toLocaleTimeString()`, and building a string with the timestamp and the message text.
 Then the message is appended to the box with the class `"log"`.

 We add a second method that logs information about `MouseEvent` based events
 (such as `mousedown`, `click`, and `mouseenter`):

```js
function logEvent(event) {
  const msg = `Event <strong>${event.type}</strong> at <em>${event.clientX}, ${event.clientY}</em>`;
  log(msg);
}
```

Then we use this as the event handler for a number of mouse events on the box that contains our log:

```js
const boxElem = document.querySelector(".box");

boxElem.addEventListener("mousedown", logEvent);
boxElem.addEventListener("mouseup", logEvent);
boxElem.addEventListener("click", logEvent);
boxElem.addEventListener("mouseenter", logEvent);
boxElem.addEventListener("mouseleave", logEvent);
```

### HTML

The HTML is quite simple for our example.

```html
<div class="box">
  <div><strong>Log:</strong></div>
  <div class="log"></div>
</div>
```

 The `<div>` with the class `"box"` is just a container for layout purposes, presenting the contents with a box around it.
 The `<div>` whose class is `"log"` is the container for the log text itself.

### CSS

The following CSS styles our example content.

```css
.box {
  width: 600px;
  height: 300px;
  border: 1px solid black;
  padding: 2px 4px;
  overflow-y: scroll;
  overflow-x: auto;
}

.log {
  margin-top: 8px;
  font-family: monospace;
}
```

### Result

 The resulting content looks like this.
 You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.

Specifications
--------------

| Specification |
| --- |
| DOM Parsing and Serialization # dom-innerhtml-innerhtml |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Node.textContent` and `HTMLElement.innerText`
* `Element.insertAdjacentHTML()`
* `Element.outerHTML`
* `Element.setHTML`
* Parsing HTML or XML into a DOM tree: `DOMParser`
* Serializing a DOM tree into an XML string: `XMLSerializer`


Element: ariaLabel property - Web APIs

Element: ariaLabel property
===========================

The **`ariaLabel`** property of the `Element` interface reflects the value of the `aria-label` attribute, which defines a string value that labels the current element.

Value
-----

A string or `null`.

Examples
--------

In this example the `aria-label` attribute on the element with an ID of `close-button` is set to "Close". Using `ariaLabel` we update the value to "Close dialog".

```html
<button aria-label="Close" id="close-button">X</button>
```

```js
let el = document.getElementById("close-button");
console.log(el.ariaLabel); // "Close"
el.ariaLabel = "Close dialog";
console.log(el.ariaLabel); // "Close dialog"
```

Specifications
--------------

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-arialabel |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Element: pointerdown event - Web APIs

Element: pointerdown event
==========================

The `pointerdown` event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons pressed to at least one button pressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.

**Note:** For touchscreen browsers that allow direct manipulation, a `pointerdown` event triggers implicit pointer capture, which causes the target to capture all subsequent pointer events as if they were occurring over the capturing target. Accordingly, `pointerover`, `pointerenter`, `pointerleave`, and `pointerout` **will not fire** as long as this capture is set. The capture can be released manually by calling `element.releasePointerCapture` on the target element, or it will be implicitly released after a `pointerup` or `pointercancel` event.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("pointerdown", (event) => {});

onpointerdown = (event) => {};
```

Event type
----------

A `PointerEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

PointerEventEvent properties
----------------

*This interface inherits properties from `MouseEvent` and `Event`.*

`PointerEvent.altitudeAngle` Read only
Experimental

Represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen.

`PointerEvent.azimuthAngle` Read only
Experimental

Represents the angle between the Y-Z plane and the plane containing both the transducer (a pointer or stylus) axis and the Y axis.

`PointerEvent.pointerId` Read only

A unique identifier for the pointer causing the event.

`PointerEvent.width` Read only

The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.height` Read only

The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.pressure` Read only

The normalized pressure of the pointer input in the range `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

`PointerEvent.tangentialPressure` Read only

The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control.

`PointerEvent.tiltX` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

`PointerEvent.tiltY` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

`PointerEvent.twist` Read only

The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

`PointerEvent.pointerType` Read only

Indicates the device type that caused the event (mouse, pen, touch, etc.).

`PointerEvent.isPrimary` Read only

Indicates if the pointer represents the primary pointer of this pointer type.

Examples
--------

Using `addEventListener()`:

```js
const para = document.querySelector("p");

para.addEventListener("pointerdown", (event) => {
  console.log("Pointer down event");
});
```

Using the `onpointerdown` event handler property:

```js
const para = document.querySelector("p");

para.onpointerdown = (event) => {
  console.log("Pointer down event");
};
```

Specifications
--------------

| Specification |
| --- |
| Pointer Events # the-pointerdown-event |
| Pointer Events # dom-globaleventhandlers-onpointerdown |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Related events
    + `gotpointercapture`
    + `lostpointercapture`
    + `pointerover`
    + `pointerenter`
    + `pointerdown`
    + `pointermove`
    + `pointerup`
    + `pointercancel`
    + `pointerout`
    + `pointerleave`
    + `pointerrawupdate`


Element: clientHeight property - Web APIs

Element: clientHeight property
==============================

 The **`Element.clientHeight`** read-only property is zero for
 elements with no CSS or inline layout boxes; otherwise, it's the inner height of an
 element in pixels. It includes padding but excludes borders, margins, and horizontal
 scrollbars (if present).

`clientHeight` can be calculated as: CSS `height` + CSS
 `padding` - height of horizontal scrollbar (if present).

 When `clientHeight` is used on the root element (the
 `<html>` element), (or on `<body>` if the document is
 in quirks mode), the viewport's height (excluding any scrollbar) is returned. This is a special case of `clientHeight`.

**Note:** This property will round the value to an integer. If you need
 a fractional value, use `element.getBoundingClientRect()`.

Value
-----

A number.

Examples
--------

![How clientHeight property determines the inner height of an element considering the height and padding](/en-US/docs/Web/API/Element/clientHeight/dimensions-client.png)

Specifications
--------------

| Specification |
| --- |
| CSSOM View Module # dom-element-clientheight |

### Notes

`clientHeight` is a property introduced in the Internet Explorer object
 model.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `HTMLElement.offsetHeight`
* `Element.scrollHeight`
* Determining the dimensions of elements


Element.ariaColIndexText - Web APIs

Element.ariaColIndexText
========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`ariaColIndexText`** property of the `Element` interface reflects the value of the `aria-colindextext` attribute, which defines a human readable text alternative of aria-colindex.

Value
-----

A string.

Examples
--------

In this example the `aria-colindex` attribute on the element with an ID of `role-heading` is set to "Aria Role column". Using `ariaColIndexText` we update the value to the string "New column name".

```html
<table
 id="semantic-table"
 role="table"
 aria-label="Semantic Elements"
 aria-describedby="semantic\_elements\_table\_desc"
 aria-rowcount="100">
  <caption id="semantic\_elements\_table\_desc">
    Semantic Elements to use instead of ARIA's roles
  </caption>
  <thead role="rowgroup">
    <tr role="row">
      <th
 role="columnheader"
 id="role-heading"
 aria-sort="none"
 aria-rowindex="1"
 aria-colindex="1"
 aria-colindextext="Aria Role column">
        ARIA Role
      </th>
      <th
 role="columnheader"
 id="element-heading"
 aria-sort="none"
 aria-rowindex="1">
        Semantic Element
      </th>
    </tr>
  </thead>
  <tbody role="rowgroup">
    <tr role="row">
      <td role="cell" aria-rowindex="11">header</td>
      <td role="cell" aria-rowindex="11">h1</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="16">header</td>
      <td role="cell" aria-rowindex="16">h6</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="18">rowgroup</td>
      <td role="cell" aria-rowindex="18">thead</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="24">term</td>
      <td role="cell" aria-rowindex="24">dt</td>
    </tr>
  </tbody>
</table>
```

```js
let el = document.getElementById("role-heading");
console.log(el.ariaColIndexText); // "Aria Role"
el.ariaColIndexText = "New column name";
console.log(el.ariaColIndexText); // "New column name"
```

Specifications
--------------

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariacolindextext |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ARIA: table role


Element: webkitmouseforcewillbegin event - Web APIs

Element: webkitmouseforcewillbegin event
========================================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Safari for macOS fires the non-standard **`webkitmouseforcewillbegin`** event at an `Element` before firing the initial `mousedown` event.

This offers the opportunity to tell the system not to trigger any default Force Touch actions if and when the click turns into a `Force Touch Events`.

To instruct macOS not to engage any default Force Touch actions if the user apply enough pressure to activate a Force Touch event, call `preventDefault()` on the `webkitmouseforcewillbegin` event object.

**`webkitmouseforcewillbegin`** is a proprietary, WebKit-specific event. It is part of the `Force Touch Events` feature.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("webkitmouseforceup", (event) => {});

onwebkitmouseforceup = (event) => {};
```

Event type
----------

A `MouseEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

MouseEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

Specifications
--------------

*Not part of any specification.* Apple has a description at the Mac Developer Library.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Introduction to events
* `webkitmouseforcedown`
* `webkitmouseforceup`
* `webkitmouseforcechanged`


Element: mouseenter event - Web APIs

Element: mouseenter event
=========================

The **`mouseenter`** event is fired at an `Element` when a pointing device (usually a mouse) is initially moved so that its hotspot is within the element at which the event was fired.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("mouseenter", (event) => {});

onmouseenter = (event) => {};
```

Event type
----------

A `MouseEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

MouseEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

Usage notes
-----------

Though similar to `mouseover`, `mouseenter` differs in that it doesn't bubble and it isn't sent to any descendants when the pointer is moved from one of its descendants' physical space to its own physical space.

### Behavior of `mouseenter` events

![Mouseenter behavior diagram](/en-US/docs/Web/API/Element/mouseenter_event/mouseenter.png)
 One `mouseenter` event is sent to each element of the hierarchy when entering them. Here 4 events are sent to the four elements of the hierarchy when the pointer reaches the text.

### Behavior of `mouseover` events

![Mouseover behavior diagram](/en-US/docs/Web/API/Element/mouseenter_event/mouseover.png)
 A single `mouseover` event is sent to the deepest element of the DOM tree, then it bubbles up the hierarchy until it is canceled by a handler or reaches the root.

With deep hierarchies, the number of `mouseover` events sent can be quite huge and cause significant performance problems. In such cases, it is better to listen for `mouseenter` events.

Combined with the corresponding `mouseleave` (which is fired at the element when the mouse exits its content area), the `mouseenter` event acts in a very similar way to the CSS `:hover` pseudo-class.

Examples
--------

The `mouseover` documentation has an example illustrating the difference between `mouseover` and `mouseenter`.

### mouseenter

The following trivial example uses the `mouseenter` event to change the border on the `div` when the mouse enters the space allotted to it. It then adds an item to the list with the number of the `mouseenter` or `mouseleave` event.

#### HTML

```html
<div id="mouseTarget">
  <ul id="unorderedList">
    <li>No events yet!</li>
  </ul>
</div>
```

#### CSS

Styling the `div` to make it more visible.

```css
#mouseTarget {
  box-sizing: border-box;
  width: 15rem;
  border: 1px solid #333;
}
```

#### JavaScript

```js
let enterEventCount = 0;
let leaveEventCount = 0;
const mouseTarget = document.getElementById("mouseTarget");
const unorderedList = document.getElementById("unorderedList");

mouseTarget.addEventListener("mouseenter", (e) => {
  mouseTarget.style.border = "5px dotted orange";
  enterEventCount++;
  addListItem(`This is mouseenter event ${enterEventCount}.`);
});

mouseTarget.addEventListener("mouseleave", (e) => {
  mouseTarget.style.border = "1px solid #333";
  leaveEventCount++;
  addListItem(`This is mouseleave event ${leaveEventCount}.`);
});

function addListItem(text) {
  // Create a new text node using the supplied text
  const newTextNode = document.createTextNode(text);

  // Create a new li element
  const newListItem = document.createElement("li");

  // Add the text node to the li element
  newListItem.appendChild(newTextNode);

  // Add the newly created list item to list
  unorderedList.appendChild(newListItem);
}
```

### Result

Specifications
--------------

| Specification |
| --- |
| UI Events # event-type-mouseenter |
| HTML Standard # handler-onmouseenter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Introduction to events
* `mousedown`
* `mouseup`
* `mousemove`
* `click`
* `dblclick`
* `mouseover`
* `mouseout`
* `mouseenter`
* `mouseleave`
* `contextmenu`


Element: ariaRequired property - Web APIs

Element: ariaRequired property
==============================

The **`ariaRequired`** property of the `Element` interface reflects the value of the `aria-required` attribute, which indicates that user input is required on the element before a form may be submitted.

**Note:** Where possible use an HTML `<input>` element with `type="text"` or a `<textarea>` as these have built in semantics and do not require ARIA attributes.

Value
-----

A string with one of the following values:

`"true"`

Users need to provide input on an element before a form is submitted.

`"false"`

User input is not necessary to submit the form.

Examples
--------

In this example the `aria-required` attribute on the element with an ID of `txtBoxInput` is set to "true" indicating that this input must be completed. Using `ariaRequired` we update the value to "false".

```html
<div id="txtboxMultilineLabel">Enter the tags for the article</div>
<div
 role="textbox"
 id="txtBoxInput"
 contenteditable="true"
 aria-multiline="true"
 aria-labelledby="txtboxMultilineLabel"
 aria-required="true"></div>
```

```js
let el = document.getElementById("txtBoxInput");
console.log(el.ariaRequired); // "true"
el.ariaRequired = "false";
console.log(el.ariaRequired); // "false"
```

Specifications
--------------

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariarequired |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ARIA: textbox role


Element: keyup event - Web APIs

Element: keyup event
====================

The **`keyup`** event is fired when a key is released.

The `keydown` and `keyup` events provide a code indicating which key is pressed, while `keypress` indicates which character was entered. For example, a lowercase "a" will be reported as 65 by `keydown` and `keyup`, but as 97 by `keypress`. An uppercase "A" is reported as 65 by all events.

Keyboard events are only generated by `<input>`, `<textarea>`, `<summary>` and anything with the `contentEditable` or `tabindex` attribute.

Since Firefox 65, the `keyup` and `keydown` events are now fired during IME composition, to improve cross-browser compatibility for CJKT users (Firefox bug 354358. To ignore all `keyup` events that are part of composition, do something like this (229 is a special value set for a `keyCode` relating to an event that has been processed by an input-method editor (IME)):

```js
eventTarget.addEventListener("keyup", (event) => {
  if (event.isComposing || event.keyCode === 229) {
    return;
  }
  // do something
});
```

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("keyup", (event) => {});

onkeyup = (event) => {};
```

Event type
----------

A `KeyboardEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

KeyboardEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`KeyboardEvent.altKey` Read only

Returns a boolean value that is `true` if the `Alt` (`Option` or `⌥` on macOS) key was active when the key event was generated.

`KeyboardEvent.code` Read only

Returns a string with the code value of the physical key represented by the event.

**Warning:** This ignores the user's keyboard layout, so that if the user presses the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return "KeyY", even if the user has a QWERTZ keyboard (which would mean the user expects a "Z" and all the other properties would indicate a "Z") or a Dvorak keyboard layout (where the user would expect an "F"). If you want to display the correct keystrokes to the user, you can use `Keyboard.getLayoutMap()`.

`KeyboardEvent.ctrlKey` Read only

Returns a boolean value that is `true` if the `Ctrl` key was active when the key event was generated.

`KeyboardEvent.isComposing` Read only

Returns a boolean value that is `true` if the event is fired between after `compositionstart` and before `compositionend`.

`KeyboardEvent.key` Read only

Returns a string representing the key value of the key represented by the event.

`KeyboardEvent.location` Read only

Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown in Keyboard locations.

`KeyboardEvent.metaKey` Read only

Returns a boolean value that is `true` if the `Meta` key (on Mac keyboards, the `⌘ Command` key; on Windows keyboards, the Windows key (`⊞`)) was active when the key event was generated.

`KeyboardEvent.repeat` Read only

Returns a boolean value that is `true` if the key is being held down such that it is automatically repeating.

`KeyboardEvent.shiftKey` Read only

Returns a boolean value that is `true` if the `Shift` key was active when the key event was generated.

Examples
--------

### addEventListener keyup example

This example logs the `KeyboardEvent.code` value whenever you release a key inside the `<input>` element.

```html
<input placeholder="Click here, then press and release a key." size="40" />
<p id="log"></p>
```

```js
const input = document.querySelector("input");
const log = document.getElementById("log");

input.addEventListener("keyup", logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}
```

### onkeyup equivalent

```js
input.onkeyup = logKey;
```

Specifications
--------------

| Specification |
| --- |
| UI Events # event-type-keyup |
| HTML Standard # handler-onkeyup |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `input`
* `keydown`
* `keypress`