Element: paste event - Web APIs

Element: paste event
====================

The **`paste`** event of the Clipboard API is fired when the user has initiated a "paste" action through the browser's user interface.

If the cursor is in an editable context (for example, in a `<textarea>` or an element with `contenteditable` attribute set to `true`) then the default action is to insert the contents of the clipboard into the document at the cursor position.

A handler for this event can access the clipboard contents by calling `getData()` on the event's `clipboardData` property.

To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using `event.preventDefault()`, and then insert its desired data manually.

It's possible to construct and dispatch a synthetic `paste` event, but this will not affect the document's contents.

This event bubbles, is cancelable and is composed.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExamples
--------

### Live example

#### HTML

```html
<div class="source" contenteditable="true">Copy text from this box.</div>
<div class="target" contenteditable="true">And paste it into this one.</div>
```

```
div.source,
div.target {
  border: 1px solid gray;
  margin: 0.5rem;
  padding: 0.5rem;
  height: 1rem;
  background-color: #e9eef1;
}
```

#### JavaScript

```js
const target = document.querySelector("div.target");

target.addEventListener("paste", (event) => {
  event.preventDefault();

  let paste = (event.clipboardData || window.clipboardData).getData("text");
  paste = paste.toUpperCase();
  const selection = window.getSelection();
  if (!selection.rangeCount) return;
  selection.deleteFromDocument();
  selection.getRangeAt(0).insertNode(document.createTextNode(paste));
  selection.collapseToEnd();
});
```

#### Result

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-paste |
| HTML Standard # handler-onpaste |

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

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

See also
--------

* Related events: `cut`, `copy`
* This event on `Document` targets: `paste`
* This event on `Window` targets: `paste`


Element: animate() method - Web APIs

Element: animate() method
=========================

Baseline 2022
-------------

Newly availableSince September 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback

 The `Element` interface's **`animate()`** method
 is a shortcut method which creates a new `Animation`, applies it to the
 element, then plays the animation. It returns the created `Animation`
 object instance.

**Note:** Elements can have multiple animations applied to them. You can get a list of the
 animations that affect an element by calling `Element.getAnimations()`.

Syntax
------

```js
animate(keyframes, options)
```

### Parameters

`keyframes`

 Either an array of keyframe objects, **or** a keyframe object whose
 properties are arrays of values to iterate over. See Keyframe Formats for more details.

`options`

 Either an **integer representing the animation's duration** (in
 milliseconds), **or** an Object containing one or more timing properties described in the `KeyframeEffect()` options parameter and/or the following options:

`id` Optional

A property unique to `animate()`: A string with which to reference the animation.

`rangeEnd` Optional

Specifies the end of an animation's attachment range along its timeline, i.e. where along the timeline an animation will end. The JavaScript equivalent of the CSS `animation-range-end` property. `rangeEnd` can take several different value types, as follows:

* A string that can be `normal` (meaning no change to the animation's attachment range), a CSS `<length-percentage>` representing an offset, a `<timeline-range-name>`, or a `<timeline-range-name>` with a `<length-percentage>` following it. For example:
```

"normal"
"entry"
"cover 100%"
```

See `animation-range` for a detailed description of the available values. Also check out the View Timeline Ranges Visualizer, which shows exactly what the different values mean in an easy visual format.
* An object containing `rangeName` (a string) and `offset` (a `CSSNumericValue`) properties representing a `<timeline-range-name>` and `<length-percentage>`, as described in the previous bullet. For example:

```js
{
  rangeName: 'entry',
  offset: CSS.percent('100'),
}
```

* A `CSSNumericValue` representing an offset, for example:

```js
CSS.percent("100");
```

`rangeStart` Optional

Specifies the start of an animation's attachment range along its timeline, i.e. where along the timeline an animation will start. The JavaScript equivalent of the CSS `animation-range-start` property. `rangeStart` can take the same value types as `rangeEnd`.

`timeline` Optional

A property unique to `animate()`: The `AnimationTimeline` to associate with the animation. Defaults to `Document.timeline`. The JavaScript equivalent of the CSS `animation-timeline` property.

### Return value

Returns an `Animation`.

Examples
--------

### Rotating and scaling

In this example we use the `animate()` method to rotate and scale an element.

#### HTML

```html
<div class="newspaper">Spinning newspaper<br />causes dizziness</div>
```

#### CSS

```css
html,
body {
  height: 100%;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: black;
}

.newspaper {
  padding: 0.5rem;
  text-transform: uppercase;
  text-align: center;
  background-color: white;
  cursor: pointer;
}
```

#### JavaScript

```js
const newspaperSpinning = [
  { transform: "rotate(0) scale(1)" },
  { transform: "rotate(360deg) scale(0)" },
];

const newspaperTiming = {
  duration: 2000,
  iterations: 1,
};

const newspaper = document.querySelector(".newspaper");

newspaper.addEventListener("click", () => {
  newspaper.animate(newspaperSpinning, newspaperTiming);
});
```

#### Result

### Down the Rabbit Hole demo

 In the demo Down the Rabbit Hole (with the Web Animation API), we use the convenient
 `animate()` method to immediately create and play an animation on the
 `#tunnel` element to make it flow upwards, infinitely. Notice the array of
 objects passed as keyframes and also the timing options block.

```js
document.getElementById("tunnel").animate(
  [
    // keyframes
    { transform: "translateY(0px)" },
    { transform: "translateY(-300px)" },
  ],
  {
    // timing options
    duration: 1000,
    iterations: Infinity,
  },
);
```

### Implicit to/from keyframes

 In newer browser versions, you are able to set a beginning or end state for an
 animation only (i.e. a single keyframe), and the browser will infer the other end of the
 animation if it is able to. For example, consider this simple animation — the Keyframe object looks like so:

```js
let rotate360 = [{ transform: "rotate(360deg)" }];
```

 We have only specified the end state of the animation, and the beginning state is
 implied.

### timeline, rangeStart, and rangeEnd

Typical usage of the `timeline`, `rangeStart`, and `rangeEnd` properties might look like this:

```js
const img = document.querySelector("img");

const timeline = new ViewTimeline({
  subject: img,
  axis: "block",
});

img.animate(
  {
    opacity: [0, 1],
    transform: ["scaleX(0)", "scaleX(1)"],
  },
  {
    fill: "both",
    duration: 1,
    timeline,
    rangeStart: "cover 0%",
    rangeEnd: "cover 100%",
  },
);
```

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

| Specification |
| --- |
| Web Animations # dom-animatable-animate |

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

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

See also
--------

* `Animation`
* `Element.getAnimations()`
* `animation-range-end`, `animation-range-start`, `animation-timeline`
* CSS scroll-driven animations
* Web Animations API


Element: animationiteration event - Web APIs

Element: animationiteration event
=================================

The **`animationiteration`** event is fired when an iteration of a CSS Animation ends, and another one begins. This event does not occur at the same time as the `animationend` event, and therefore does not occur for animations with an `animation-iteration-count` of one.

Syntax
------

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

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

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

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

An `AnimationEvent`. Inherits from `Event`.

Event

AnimationEventEvent properties
----------------

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

`AnimationEvent.animationName` Read only

A string containing the value of the `animation-name` that generated the animation.

`AnimationEvent.elapsedTime` Read only

A `float` giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an `animationstart` event, `elapsedTime` is `0.0` unless there was a negative value for `animation-delay`, in which case the event will be fired with `elapsedTime` containing `(-1 * delay)`.

`AnimationEvent.pseudoElement` Read only

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

Examples
--------

This code uses `animationiteration` to keep track of the number of iterations an animation has completed:

```js
const animated = document.querySelector(".animated");

let iterationCount = 0;

animated.addEventListener("animationiteration", () => {
  iterationCount++;
  console.log(`Animation iteration count: ${iterationCount}`);
});
```

The same, but using the `onanimationiteration` event handler property:

```js
const animated = document.querySelector(".animated");

let iterationCount = 0;

animated.onanimationiteration = () => {
  iterationCount++;
  console.log(`Animation iteration count: ${iterationCount}`);
};
```

### Live example

#### HTML

```html
<div class="animation-example">
  <div class="container">
    <p class="animation">You chose a cold night to visit our planet.</p>
  </div>
  <button class="activate" type="button">Activate animation</button>
  <div class="event-log"></div>
</div>
```

#### CSS

```css
.container {
  height: 3rem;
}

.event-log {
  width: 25rem;
  height: 2rem;
  border: 1px solid black;
  margin: 0.2rem;
  padding: 0.2rem;
}

.animation.active {
  animation-duration: 2s;
  animation-name: slidein;
  animation-iteration-count: 2;
}

@keyframes slidein {
  from {
    transform: translateX(100%) scaleX(3);
  }
  to {
    transform: translateX(0) scaleX(1);
  }
}
```

#### JavaScript

```js
const animation = document.querySelector("p.animation");
const animationEventLog = document.querySelector(
  ".animation-example>.event-log",
);
const applyAnimation = document.querySelector(
  ".animation-example>button.activate",
);
let iterationCount = 0;

animation.addEventListener("animationstart", () => {
  animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `;
});

animation.addEventListener("animationiteration", () => {
  iterationCount++;
  animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `;
});

animation.addEventListener("animationend", () => {
  animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`;
  animation.classList.remove("active");
  applyAnimation.textContent = "Activate animation";
});

animation.addEventListener("animationcancel", () => {
  animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`;
});

applyAnimation.addEventListener("click", () => {
  animation.classList.toggle("active");
  animationEventLog.textContent = "";
  iterationCount = 0;
  const active = animation.classList.contains("active");
  applyAnimation.textContent = active
    ? "Cancel animation"
    : "Activate animation";
});
```

#### Result

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

| Specification |
| --- |
| CSS Animations Level 1 # eventdef-globaleventhandlers-animationiteration |

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

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

See also
--------

* CSS Animations
* Using CSS Animations
* `AnimationEvent`
* Related events: `animationstart`, `animationend`, `animationcancel`


Element: transitionend event - Web APIs

Element: transitionend event
============================

The **`transitionend`** event is fired when a CSS transition has completed. In the case where a transition is removed before completion, such as if the `transition-property` is removed or `display` is set to `none`, then the event will not be generated.

The `transitionend` event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. If the `transitioncancel` event is fired, the `transitionend` event will not fire.

This event is not cancelable.

Syntax
------

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

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

ontransitionend = (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 gets an element that has a transition defined and adds a listener to the `transitionend` event:

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

transition.addEventListener("transitionend", () => {
  console.log("Transition ended");
});
```

The same, but using `ontransitionend`:

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

transition.ontransitionend = () => {
  console.log("Transition ended");
};
```

### 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 that the `transitionstart`, `transitionrun`, `transitioncancel` and `transitionend` events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends.

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

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

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

el.addEventListener("transitioncancel", () => {
  message.textContent = "transitioncancel fired";
});

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

The `transitionend` event is fired in both directions: when the box finishes turning and the opacity hits 0 or 1, depending on the direction.

If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired.

If the `transitioncancel` event is fired, the `transitionend` event will not fire.

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

| Specification |
| --- |
| CSS Transitions # transitionend |

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: `transitionrun`, `transitionstart`, `transitioncancel`


Element: ariaValueMax property - Web APIs

Element: ariaValueMax property
==============================

The **`ariaValueMax`** property of the `Element` interface reflects the value of the `aria-valuemax` attribute, which defines the maximum allowed value for a range widget.

Value
-----

A string which contains a number.

Examples
--------

In this example the `aria-valuemax` attribute on the element with an ID of `slider` is set to "7". Using `ariaValueMax` we update the value to "6".

```html
<div
 role="slider"
 aria-valuenow="1"
 aria-valuemin="1"
 aria-valuemax="7"
 aria-valuetext="Sunday"></div>
```

```js
let el = document.getElementById("slider");
console.log(el.ariaValueMax); // 7
el.ariaValueMax = "6";
console.log(el.ariaValueMax); // 6
```

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

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

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

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


Element: DOMActivate event - Web APIs

Element: DOMActivate 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 **`DOMActivate`** event is fired at an element when it becomes active, such as when it is clicked on using the mouse or a keypress is used to navigate to it.

Syntax
------

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

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

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

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

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

Event

UIEvent

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

[...]

Examples
--------

```html
<svg
 xmlns="http://www.w3.org/2000/svg"
 version="1.2"
 baseProfile="tiny"
 xmlns:ev="http://www.w3.org/2001/xml-events"
 width="6cm"
 height="5cm"
 viewBox="0 0 600 500">
  <desc>Example: invoke an ECMAScript function from a DOMActivate event</desc>

  <!-- ECMAScript to change the radius -->
  <script type="application/ecmascript">
 <![CDATA[ function change(evt) { const circle = evt.target; const
 currentRadius = circle.getFloatTrait("r"); if (currentRadius === 100) {
 circle.setFloatTrait("r", currentRadius \* 2); } else {
 circle.setFloatTrait("r", currentRadius \* 0.5); } } ]]>
 </script>

  <!-- Act on each DOMActivate event -->
  <circle cx="300" cy="225" r="100" fill="red">
    <handler type="application/ecmascript" ev:event="DOMActivate">
      change(evt);
    </handler>
  </circle>

  <text
 x="300"
 y="480"
 font-family="Verdana"
 font-size="35"
 text-anchor="middle">
    Activate the circle to change its size
  </text>
</svg>
```

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

| Specification |
| --- |
| UI Events # event-type-DOMActivate |

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

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

See also
--------

* `MouseEvent`
* `mousedown`
* `mouseup`
* `mousemove`


Element: ariaValueMin property - Web APIs

Element: ariaValueMin property
==============================

The **`ariaValueMin`** property of the `Element` interface reflects the value of the `aria-valuemin` attribute, which defines the minimum allowed value for a range widget.

Value
-----

A string which contains a number.

Examples
--------

In this example the `aria-valuemin` attribute on the element with an ID of `slider` is set to "1". Using `ariaValueMin` we update the value to "2".

```html
<div
 role="slider"
 aria-valuenow="1"
 aria-valuemin="1"
 aria-valuemax="7"
 aria-valuetext="Sunday"></div>
```

```js
let el = document.getElementById("slider");
console.log(el.ariaValueMin); // 1
el.ariaValueMin = "2";
console.log(el.ariaValueMin); // 2
```

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

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

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

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


Element: pointerleave event - Web APIs

Element: pointerleave event
===========================

The `pointerleave` event is fired when a pointing device is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the 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("pointerleave", (event) => {});

onpointerleave = (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("pointerleave", (event) => {
  console.log("Pointer left element");
});
```

Using the `onpointerleave` event handler property:

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

para.onpointerleave = (event) => {
  console.log("Pointer left element");
};
```

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

| Specification |
| --- |
| Pointer Events # the-pointerleave-event |
| Pointer Events # dom-globaleventhandlers-onpointerleave |

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: pointerenter event - Web APIs

Element: pointerenter event
===========================

The `pointerenter` event fires when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a `pointerdown` event from a device that does not support hover (see `pointerdown`).

Syntax
------

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

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

onpointerenter = (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("pointerenter", (event) => {
  console.log("Pointer entered element");
});
```

Using the `onpointerenter` event handler property:

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

para.onpointerenter = (event) => {
  console.log("Pointer entered element");
};
```

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

| Specification |
| --- |
| Pointer Events # the-pointerenter-event |
| Pointer Events # dom-globaleventhandlers-onpointerenter |

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: scrollTo() method - Web APIs

Element: scrollTo() method
==========================

 The **`scrollTo()`** method of the `Element`
 interface scrolls to a particular set of coordinates inside a given element.

Syntax
------

```js
scrollTo(x-coord, y-coord)
scrollTo(options)
```

### Parameters

* `x-coord` is the pixel along the horizontal axis of the
 element that you want displayed in the upper left.
* `y-coord` is the pixel along the vertical axis of the element
 that you want displayed in the upper left.

- or -

`options`

A dictionary containing the following parameters:

`top`

Specifies the number of pixels along the Y axis to scroll the window or element.

`left`

Specifies the number of pixels along the X axis to scroll the window or element.

`behavior`

Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:

* `smooth`: scrolling should animate smoothly
* `instant`: scrolling should happen instantly in a single jump
* `auto`: scroll behavior is determined by the computed value of `scroll-behavior`

### Return value

None (`undefined`).

Examples
--------

```js
element.scrollTo(0, 1000);
```

Using `options`:

```js
element.scrollTo({
  top: 100,
  left: 100,
  behavior: "smooth",
});
```

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

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

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

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

See also
--------

* `Element.scrollTop`, `Element.scrollLeft`
* `Window.scrollTo()`


Element: requestFullscreen() method - Web APIs

Element: requestFullscreen() method
===================================

 The **`Element.requestFullscreen()`**
 method issues an asynchronous request to make the element be displayed in fullscreen
 mode.

 It's not guaranteed that the element will be put into full screen mode. If permission
 to enter full screen mode is granted, the returned `Promise` will resolve
 and the element will receive a `fullscreenchange` event to let it know that
 it's now in full screen mode. If permission is denied, the promise is rejected and the
 element receives a `fullscreenerror` event instead. If the element has been
 detached from the original document, then the document receives these events instead.

Syntax
------

```js
requestFullscreen()
requestFullscreen(options)
```

### Parameters

`options` Optional

An object that controls the behavior of the transition to fullscreen mode. The available options are:

`navigationUI` Optional

 Controls whether or not to show navigation UI while the element is in fullscreen mode.
 The default value is `"auto"`, which indicates that the browser should decide what to do.

`"hide"`

 The browser's navigation interface will be hidden
 and the entire dimensions of the screen will be allocated to the display of the element.

`"show"`

 The browser will present page navigation controls and possibly other
 user interface; the dimensions of the element (and the perceived size of the screen) will be clamped
 to leave room for this user interface.

`"auto"`

 The browser will choose which of the above settings to apply.
 This is the default value.

`screen` Optional
Experimental

Specifies on which screen you want to put the element in fullscreen mode. This takes a `ScreenDetailed` object as a value, representing the chosen screen.

### Return value

 A `Promise` which is resolved with a value of `undefined` when
 the transition to full screen is complete.

### Exceptions

*Rather than throw a traditional exception, the `requestFullscreen()`
procedure announces error conditions by rejecting the `Promise` it has
returned. The rejection handler receives one of the following exception values:*

`TypeError`

 The `TypeError` exception may be delivered in any of the following
 situations:

* The document containing the element isn't fully active; that is, it's not the
 current active document.
* The element is not contained by a document.
* The element is not permitted to use the `fullscreen` feature,
 either because of Permissions Policy configuration or other access control features.
* The element and its document are the same node.
* The element is a popover that is already being shown via `HTMLElement.showPopover()`.

Security
--------

Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.

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

### Compatible elements

 An element that you wish to place into fullscreen mode has to meet a small number of
 simple requirements:

* It must be one of the standard HTML elements or `<svg>` or
 `<math>`.
* It is *not* a `<dialog>` element.
* It must either be located within the top-level document or in an
 `<iframe>` which has the `allowfullscreen`
 attribute applied to it.

Additionally, any set Permissions Policies must allow the use of this feature.

### Detecting fullscreen activation

 You can determine whether or not your attempt to switch to fullscreen mode is
 successful by using the `Promise` returned by
 `requestFullscreen()`, as seen in the examples below.

 To learn when other code has toggled fullscreen mode on and off, you should establish
 listeners for the `fullscreenchange` event on the `Document`.
 It's also important to listen for `fullscreenchange` to be aware when, for
 example, the user manually toggles fullscreen mode, or when the user switches
 applications, causing your application to temporarily exit fullscreen mode.

Examples
--------

### Requesting fullscreen mode

 This function toggles the first `<video>` element found in the document
 into and out of fullscreen mode.

```js
function toggleFullscreen() {
  let elem = document.querySelector("video");

  if (!document.fullscreenElement) {
    elem.requestFullscreen().catch((err) => {
      alert(
        `Error attempting to enable fullscreen mode: ${err.message} (${err.name})`,
      );
    });
  } else {
    document.exitFullscreen();
  }
}
```

 If the document isn't already in fullscreen mode—detected by looking to see if
 `document.fullscreenElement` has a value—we call the video's
 `requestFullscreen()` method. We don't need to do anything special if
 successful, but if the request fails, our promise's `catch()` handler
 presents an alert with an appropriate error message.

 If, on the other hand, fullscreen mode is already in effect, we call
 `document.exitFullscreen()` to disable fullscreen mode.

You can see this example in action or view or remix the code on Glitch.

### Using navigationUI

 In this example, the entire document is placed into fullscreen mode by calling
 `requestFullscreen()` on the document's
 `Document.documentElement`, which is the document's root
 `<html>` element.

```js
let elem = document.documentElement;

elem
  .requestFullscreen({ navigationUI: "show" })
  .then(() => {})
  .catch((err) => {
    alert(
      `An error occurred while trying to switch into fullscreen mode: ${err.message} (${err.name})`,
    );
  });
```

 The promise's resolve handler does nothing, but if the promise is rejected, an error
 message is displayed by calling `alert()`.

### Using the screen option

If you wanted to make the element fullscreen on the primary OS screen, you could use code like the following:

```js
try {
  const primaryScreen = (await getScreenDetails()).screens.find(
    (screen) => screen.isPrimary,
  );
  await document.body.requestFullscreen({ screen: primaryScreen });
} catch (err) {
  console.error(err.name, err.message);
}
```

The `Window.getScreenDetails()` method is used to retrieve the `ScreenDetails` object for the current device, which contains `ScreenDetailed` objects representing the different available screens.

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

| Specification |
| --- |
| Fullscreen API Standard # ref-for-dom-element-requestfullscreen① |

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

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

See also
--------

* Fullscreen API
* `Document.exitFullscreen()`
* `Document.fullscreen`
* `Document.fullscreenElement`
* `:fullscreen`
* `allowfullscreen`


Element: pointermove event - Web APIs

Element: pointermove event
==========================

The `pointermove` event is fired when a pointer changes coordinates, and the pointer has not been canceled by a browser touch-action.

Syntax
------

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

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

onpointermove = (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.

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

The event, which is of type `PointerEvent`, provides all the information you need to know about the user's interaction with the pointing device, including the position, movement distance, button states, and much more.

Examples
--------

To add a handler for `pointermove` events using `addEventListener()`:

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

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

You can also use the `onpointermove` event handler property:

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

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

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

| Specification |
| --- |
| Pointer Events # the-pointermove-event |
| Pointer Events # dom-globaleventhandlers-onpointermove |

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: setHTML() method - Web APIs

Element: setHTML() method
=========================

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

 The **`setHTML()`** method of the `Element` interface is used to parse and sanitize a string of HTML and then insert it into the DOM as a subtree of the element.
 It should be used instead of `Element.innerHTML` for inserting untrusted strings of HTML into an element.

 The parsing process drops any elements in the HTML string that are invalid in the context of the current element, while sanitizing removes any unsafe or otherwise unwanted elements, attributes or comments.
 The default `Sanitizer()` configuration strips out XSS-relevant input by default, including `<script>` tags, custom elements, and comments.
 The sanitizer configuration may be customized using `Sanitizer()` constructor options.

Syntax
------

```js
setHTML(input, options)
```

### Parameters

`input`

A string defining HTML to be sanitized.

`options` Optional

An options object with the following optional parameters:

`sanitizer`

 A `Sanitizer` object which defines what elements of the input will be sanitized.
 If not specified, the default `Sanitizer` object is used.

### Return value

None (`undefined`).

### Exceptions

None.

Examples
--------

The code below demonstrates how to sanitize a string of HTML and insert it into the `Element` with an id of `target`.

```js
const unsanitized_string = "abc <script>alert(1)<" + "/script> def"; // Unsanitized string of HTML
const sanitizer1 = new Sanitizer(); // Default sanitizer;

// Get the Element with id "target" and set it with the sanitized string.
document
  .getElementById("target")
  .setHTML(unsanitized_string, { sanitizer: sanitizer1 });

// Result (as a string): "abc def"
```

**Note:** This example uses the default sanitizer.
 The `Sanitizer` constructor is used to configure sanitizer options.

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

| Specification |
| --- |
| HTML Sanitizer API # dom-element-sethtml |

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

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


Element: transitioncancel event - Web APIs

Element: transitioncancel event
===============================

The **`transitioncancel`** event is fired when a CSS transition is canceled.

Syntax
------

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

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

ontransitioncancel = (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 gets an element that has a transition defined and adds a listener to the `transitioncancel` event:

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

transition.addEventListener("transitioncancel", () => {
  console.log("Transition canceled");
});
```

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

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

transition.ontransitioncancel = () => {
  console.log("Transition canceled");
};
```

### Live example

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

```html
<div class="transition"></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: 2s;
}

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

To this, we'll add some JavaScript to indicate that the `transitionstart`, `transitionrun`, `transitioncancel`, and `transitionend` events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends.

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

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

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

el.addEventListener("transitioncancel", () => {
  message.textContent = "transitioncancel fired";
});

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

The `transitioncancel` event is fired if the transition is cancelled in either direction after the `transitionrun` event occurs and before the `transitionend` is fired.

If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired.

If the `transitioncancel` event is fired, the `transitionend` event will not fire.

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

| Specification |
| --- |
| CSS Transitions # transitioncancel |
| CSS Transitions # dom-globaleventhandlers-ontransitioncancel |

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: `transitionrun`, `transitionstart`, `transitionend`


Element: insertAdjacentElement() method - Web APIs

Element: insertAdjacentElement() method
=======================================

 The **`insertAdjacentElement()`** method of the
 `Element` interface inserts a given element node at a given position
 relative to the element it is invoked upon.

Syntax
------

```js
insertAdjacentElement(position, element)
```

### Parameters

`position`

 A string representing the position relative to the
 `targetElement`; must match (case-insensitively) one of the following
 strings:

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

`element`

The element to be inserted into the tree.

### Return value

The element that was inserted, or `null`, if the insertion failed.

### Exceptions

* `SyntaxError` `DOMException`
    + Thrown if the `position` specified is not a recognized value.
* `TypeError`
    + Thrown if the `element` specified is not a valid element.
### 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", () => {
  const tempDiv = document.createElement("div");
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement("beforebegin", tempDiv);
  }
  setListener(tempDiv);
});

afterBtn.addEventListener("click", () => {
  const tempDiv = document.createElement("div");
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement("afterend", tempDiv);
  }
  setListener(tempDiv);
});
```

 Have a look at our insertAdjacentElement.html
 demo on GitHub (see the source code too.) Here, we have a sequence of `<div>` elements inside a
 container. When one is clicked, it becomes selected and you can then press the
 *Insert before* and *Insert after* buttons to insert new divs before or
 after the selected element using `insertAdjacentElement()`.

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

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

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

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

See also
--------

* `Element.insertAdjacentHTML()`
* `Element.insertAdjacentText()`
* `Node.insertBefore()` (similar to `beforebegin`, with
 different arguments)
* `Node.appendChild()` (same effect as `beforeend`)


Element: fullscreenerror event - Web APIs

Element: fullscreenerror event
==============================

The `fullscreenerror` event is fired when the browser cannot switch to fullscreen mode.

As with the `fullscreenchange` event, two `fullscreenerror` events are fired; the first is sent to the `Element` which failed to change modes, and the second is sent to the `Document` which owns that element.

For some reasons that switching into fullscreen mode might fail, see the guide to the Fullscreen API.

This event is not cancelable.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
const requestor = document.querySelector("div");

function handleError(event) {
  console.error("an error occurred changing into fullscreen");
  console.log(event);
}

requestor.addEventListener("fullscreenerror", handleError);
// or
requestor.onfullscreenerror = handleError;

requestor.requestFullscreen();
```

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

| Specification |
| --- |
| Fullscreen API Standard # handler-document-onfullscreenerror |

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

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

See also
--------

* `fullscreenchange`
* Fullscreen API
* Guide to the Fullscreen API


Element: gesturestart event - Web APIs

Element: gesturestart 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.

The **`gesturestart`** event is fired when multiple fingers contact the touch surface, thus starting a new gesture. During the gesture, `gesturechange` events will be fired. When the gesture has ended, a `gestureend` event will be fired.

It is a proprietary event specific to WebKit.

Syntax
------

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

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

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

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

A `GestureEvent`. Inherits from `Event`.

Event properties
----------------

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

`GestureEvent.rotation` Read only

Change in rotation (in degrees) since the event's beginning. Positive values indicate clockwise rotation; negative values indicate counterclockwise rotation. Initial value: `0.0`.

`GestureEvent.scale` Read only

Distance between two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the gesture. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: `1.0`.

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

* GestureEventClassReference at the Safari Developer Library


Element: touchmove event - Web APIs

Element: touchmove event
========================

The `touchmove` event is fired when one or more touch points are moved along the touch surface.

Syntax
------

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

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

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

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

A `TouchEvent`. Inherits from `Event`.

Event

UIEvent

TouchEventEvent properties
----------------

*This interface inherits properties from its parent, `UIEvent` and `Event`.*

`TouchEvent.altKey` Read only

A Boolean value indicating whether or not the alt key was down when the touch event was fired.

`TouchEvent.changedTouches` Read only

A `TouchList` of all the `Touch` objects representing individual points of contact whose states changed between the previous touch event and this one.

`TouchEvent.ctrlKey` Read only

A Boolean value indicating whether or not the control key was down when the touch event was fired.

`TouchEvent.metaKey` Read only

A Boolean value indicating whether or not the meta key was down when the touch event was fired.

`TouchEvent.shiftKey` Read only

A Boolean value indicating whether or not the shift key was down when the touch event was fired.

`TouchEvent.targetTouches` Read only

A `TouchList` of all the `Touch` objects that are both currently in contact with the touch surface **and** were also started on the same element that is the target of the event.

`TouchEvent.touches` Read only

A `TouchList` of all the `Touch` objects representing all current points of contact with the surface, regardless of target or changed status.

`TouchEvent.rotation`
Non-standard
 Read only

Change in rotation (in degrees) since the event's beginning. Positive values indicate clockwise rotation; negative values indicate counterclockwise rotation. Initial value: `0.0`.

`TouchEvent.scale`
Non-standard
 Read only

Distance between two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the event. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: `1.0`.

Examples
--------

Code samples for those events are available on the dedicated page: Touch events.

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

| Specification |
| --- |
| Touch Events # event-touchmove |
| Touch Events # dom-globaleventhandlers-ontouchmove |

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

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

See also
--------

* Touch events
* `mousemove`


Element: focusin event - Web APIs

Element: focusin event
======================

The **`focusin`** event fires when an element has received focus, after the `focus` event. The two events differ in that `focusin` bubbles, while `focus` does not.

The opposite of `focusin` is the `focusout` event, which fires when the element has lost focus.

The `focusin` event is not cancelable.

Syntax
------

Use the event name in methods like `addEventListener()`.

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

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

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

Event

UIEvent

FocusEventEvent properties
----------------

*This interface also inherits properties from its parent `UIEvent`, and indirectly from `Event`*.

`FocusEvent.relatedTarget`

The element losing focus, if any.

Examples
--------

### Live example

#### HTML

```html
<form id="form">
  <label>
    Some text:
    <input type="text" placeholder="text input" />
  </label>
  <label>
    Password:
    <input type="password" placeholder="password" />
  </label>
</form>
```

#### JavaScript

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

form.addEventListener("focusin", (event) => {
  event.target.style.background = "pink";
});

form.addEventListener("focusout", (event) => {
  event.target.style.background = "";
});
```

#### Result

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

| Specification |
| --- |
| UI Events # event-type-focusin |

**Note:** The *UI Events* specification describes an order of focus events that's different from what current browsers implement.

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

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

See also
--------

* Related events: `blur`, `focus`, `focusout`
* Focusing: focus/blur


Element: touchstart event - Web APIs

Element: touchstart event
=========================

The `touchstart` event is fired when one or more touch points are placed on the touch surface.

Syntax
------

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

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

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

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

A `TouchEvent`. Inherits from `Event`.

Event

UIEvent

TouchEventEvent properties
----------------

*This interface inherits properties from its parent, `UIEvent` and `Event`.*

`TouchEvent.altKey` Read only

A Boolean value indicating whether or not the alt key was down when the touch event was fired.

`TouchEvent.changedTouches` Read only

A `TouchList` of all the `Touch` objects representing individual points of contact whose states changed between the previous touch event and this one.

`TouchEvent.ctrlKey` Read only

A Boolean value indicating whether or not the control key was down when the touch event was fired.

`TouchEvent.metaKey` Read only

A Boolean value indicating whether or not the meta key was down when the touch event was fired.

`TouchEvent.shiftKey` Read only

A Boolean value indicating whether or not the shift key was down when the touch event was fired.

`TouchEvent.targetTouches` Read only

A `TouchList` of all the `Touch` objects that are both currently in contact with the touch surface **and** were also started on the same element that is the target of the event.

`TouchEvent.touches` Read only

A `TouchList` of all the `Touch` objects representing all current points of contact with the surface, regardless of target or changed status.

`TouchEvent.rotation`
Non-standard
 Read only

Change in rotation (in degrees) since the event's beginning. Positive values indicate clockwise rotation; negative values indicate counterclockwise rotation. Initial value: `0.0`.

`TouchEvent.scale`
Non-standard
 Read only

Distance between two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the event. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: `1.0`.

Examples
--------

Code samples for those events are available on the dedicated page: Touch events.

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

| Specification |
| --- |
| Touch Events # event-touchstart |
| Touch Events # dom-globaleventhandlers-ontouchstart |

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

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

See also
--------

* Touch events


Element: prefix property - Web APIs

Element: prefix property
========================

 The **`Element.prefix`** read-only property returns the
 namespace prefix of the specified element, or `null` if no prefix is
 specified.

Value
-----

A string.

Examples
--------

The following logs "x" to the console.

```xml
<x:div onclick="console.log(this.prefix)"/>
```

Notes
-----

 This will only work when a namespace-aware parser is used, i.e. when a document is
 served with an XML MIME type. This will not work for HTML documents.

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

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

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

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

See also
--------

* `Element.namespaceURI`
* `Element.localName`
* `Attr.prefix`


Element: hasAttributeNS() method - Web APIs

Element: hasAttributeNS() method
================================

`hasAttributeNS` returns a boolean value indicating whether the current element has the specified attribute.

Syntax
------

```js
hasAttributeNS(namespace,localName)
```

### Parameters

* `namespace` is a string specifying the namespace of the attribute.
* `localName` is the name of the attribute.
### Return value

A boolean.

Examples
--------

```js
// Check that the attribute exists before you set a value
const d = document.getElementById("div1");
if (
  d.hasAttributeNS("http://www.mozilla.org/ns/specialspace/", "special-align")
) {
  d.setAttribute("align", "center");
}
```

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-hasattributens① |

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

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


Element: querySelectorAll() method - Web APIs

Element: querySelectorAll() method
==================================

 The `Element` method **`querySelectorAll()`**
 returns a static (not live) `NodeList` representing a list of elements
 matching the specified group of selectors which are descendants of the element on which
 the method was called.

Syntax
------

```js
querySelectorAll(selectors)
```

### Parameters

`selectors`

 A string containing one or more selectors to match against. This
 string must be a valid CSS selector
 string; if it's not, a `SyntaxError` exception is thrown. See Locating DOM elements using selectors for more information about using selectors to
 identify elements. Multiple selectors may be specified by separating them using
 commas.

Note that the selectors are applied to the entire document, not just the particular element on which `querySelectorAll()` is called. To restrict the selector to the element on which `querySelectorAll()` is called, include the `:scope` pseudo-class at the start of the selector. See the selector scope example.

**Note:** Characters which are not part of standard CSS syntax must be
 escaped using a backslash character. Since JavaScript also uses backslash escaping,
 special care must be taken when writing string literals using these characters. See
 Escaping special characters for more information.

### Return value

 A non-live `NodeList` containing one `Element` object for
 each descendant node that matches at least one of the specified selectors.

**Note:** If the specified `selectors` include a CSS pseudo-element, the returned list
 is always empty.

### Exceptions

`SyntaxError` `DOMException`

Thrown if the syntax of the specified `selectors` string is not valid.

Examples
--------

### dataset selector & attribute selectors

```html
<section class="box" id="sect1">
  <div class="funnel-chart-percent1">10.900%</div>
  <div class="funnel-chart-percent2">3700.00%</div>
  <div class="funnel-chart-percent3">0.00%</div>
</section>
```

```js
// dataset selectors
const refs = [
  ...document.querySelectorAll(`[data-name\*="funnel-chart-percent"]`),
];

// attribute selectors
// const refs = [...document.querySelectorAll(`[class\*="funnel-chart-percent"]`)];
// const refs = [...document.querySelectorAll(`[class^="funnel-chart-percent"]`)];
// const refs = [...document.querySelectorAll(`[class$="funnel-chart-percent"]`)];
// const refs = [...document.querySelectorAll(`[class~="funnel-chart-percent"]`)];
```

### Obtaining a list of matches

 To obtain a `NodeList` of all of the `<p>` elements
 contained within the element `"myBox"`:

```js
const matches = myBox.querySelectorAll("p");
```

 This example returns a list of all `<div>` elements within
 `"myBox"` with a class of either "`note`" or "`alert`":

```js
const matches = myBox.querySelectorAll("div.note, div.alert");
```

 Here, we get a list of the document's `<p>` elements whose immediate
 parent element is a `<div>` with the class `"highlighted"` and
 which are located inside a container whose ID is `"test"`.

```js
const container = document.querySelector("#test");
const matches = container.querySelectorAll("div.highlighted > p");
```

 This example uses an attribute selector to return a list of the `<iframe>` elements in the document
 that contain an attribute named `"data-src"`:

```js
const matches = document.querySelectorAll("iframe[data-src]");
```

 Here, an attribute selector is used to return a list of the list items contained within
 a list whose ID is `"userlist"` which have a `"data-active"`
 attribute whose value is `"1"`:

```js
const container = document.querySelector("#userlist");
const matches = container.querySelectorAll("li[data-active='1']");
```

### Accessing the matches

 Once the `NodeList` of matching elements is returned, you can examine it
 just like any array. If the array is empty (that is, its `length` property is
 `0`), then no matches were found.

 Otherwise, you can use standard array notation to access the contents of the list. You
 can use any common looping statement, such as:

```js
const highlightedItems = userList.querySelectorAll(".highlighted");

highlightedItems.forEach((userItem) => {
  deleteUser(userItem);
});
```

**Note:** `NodeList` is not a genuine array, that is to say it doesn't
 have array methods like `slice`, `some`, `map`, etc. To convert it into an array, try
 `Array.from(nodeList)`.

### Selector scope

The `querySelectorAll()` method applies its selectors to the whole document: they are not scoped to the element on which the method is called. To scope the selectors, include the `:scope` pseudo-class at the start of the selector string.

#### HTML

In this example the HTML contains:

* two buttons: `#select` and `#select-scope`
* three nested `<div>` elements:`#outer`, `#subject`, and `#inner`
* a `<pre>` element which the example uses for output.

```html
<button id="select">Select</button>
<button id="select-scope">Select with :scope</button>

<div id="outer">
  .outer
  <div id="subject">
    .subject
    <div id="inner">.inner</div>
  </div>
</div>

<pre id="output"></pre>
```

```
div {
  margin: 0.5rem;
  padding: 0.5rem;
  border: 3px #20b2aa solid;
  border-radius: 5px;
  font-family: monospace;
}

pre,
button {
  margin: 0.5rem;
  padding: 0.5rem;
}
```

#### JavaScript

In the JavaScript, we first select the `#subject` element.

When the `#select` button is pressed, we call `querySelectorAll()` on `#subject`, passing `"#outer #inner"` as the selector string.

When the `#select-scope` button is pressed, we again call `querySelectorAll()` on `#subject`, but this time we pass `":scope #outer #inner"` as the selector string.

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

const select = document.querySelector("#select");
select.addEventListener("click", () => {
  const selected = subject.querySelectorAll("#outer #inner");
  output.textContent = `Selection count: ${selected.length}`;
});

const selectScope = document.querySelector("#select-scope");
selectScope.addEventListener("click", () => {
  const selected = subject.querySelectorAll(":scope #outer #inner");
  output.textContent = `Selection count: ${selected.length}`;
});
```

#### Result

When we press "Select", the selector selects all elements with an ID of `inner` that also have an ancestor with an ID of `outer`. Note that even though `#outer` is outside the `#subject` element, it is still used in selection, so our `#inner` element is found.

When we press "Select with :scope", the `:scope` pseudo-class restricts the selector scope to `#subject`, so `#outer` is not used in selector matching, and we don't find the `#inner` element.

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-parentnode-queryselectorall① |

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

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

See also
--------

* Locating DOM elements using selectors
* Attribute selectors in the CSS
 Guide
* Attribute selectors in the MDN Learning Area
* `Element.querySelector()`
* `Document.querySelector()` and
 `Document.querySelectorAll()`
* `DocumentFragment.querySelector()` and
 `DocumentFragment.querySelectorAll()`


Element: input event - Web APIs

Element: input event
====================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`input`** event fires when the `value` of an `<input>`, `<select>`, or `<textarea>` element has been changed as a direct result of a user action (such as typing in a textbox or checking a checkbox).

The event also applies to elements with `contenteditable` enabled, and to any element when `designMode` is turned on. In the case of `contenteditable` and `designMode`, the event target is the *editing host*. If these properties apply to multiple elements, the editing host is the nearest ancestor element whose parent isn't editable.

For `<input>` elements with `type=checkbox` or `type=radio`, the `input` event should fire whenever a user toggles the control, per the HTML Living Standard specification. However, historically this has not always been the case. Check compatibility, or use the `change` event instead for elements of these types.

For `<textarea>` and `<input>` elements that accept text input (`type=text`, `type=tel`, etc.), the interface is `InputEvent`; for others, the interface is `Event`.

The `input` event is fired every time the `value` of the element changes. This is unlike the `change` event, which only fires when the value is committed, such as by pressing the enter key or selecting a value from a list of options. Note that the `input` event is not fired when JavaScript changes an element's `value` programmatically.

Syntax
------

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

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

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

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

An `InputEvent`. Inherits from `UIEvent`.

Event

UIEvent

InputEventEvent properties
----------------

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

`InputEvent.data` Read only

Returns a string with the inserted characters. This may be an empty string if the change doesn't insert text (for example, when deleting characters).

`InputEvent.dataTransfer` Read only

Returns a `DataTransfer` object containing information about richtext or plaintext data being added to or removed from editable content.

`InputEvent.inputType` Read only

Returns the type of change for editable content such as, for example, inserting, deleting, or formatting text.

`InputEvent.isComposing` Read only

Returns a `Boolean` value indicating if the event is fired after `compositionstart` and before `compositionend`.

Examples
--------

This example logs the value whenever you change the value of the `<input>` element.

### HTML

```html
<input placeholder="Enter some text" name="name" />
<p id="values"></p>
```

### JavaScript

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

input.addEventListener("input", updateValue);

function updateValue(e) {
  log.textContent = e.target.value;
}
```

### Result

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

| Specification |
| --- |
| UI Events # event-type-input |
| HTML Standard # handler-oninput |

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

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

See also
--------

* Related events
    + `beforeinput`
    + `change`
    + `invalid`


Element: webkitmouseforcechanged event - Web APIs

Element: webkitmouseforcechanged 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.

The non-standard **`webkitmouseforcechanged`** event is fired by Safari each time the amount of pressure changes on the trackpad/touchscreen.

**`webkitmouseforcechanged`** is a proprietary, WebKit-specific event introduced by Apple to support their `Force Touch Events` feature.

This event first fires after the `mousedown` event and stops firing before the `mouseup` event.

Syntax
------

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

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

onwebkitmouseforcechanged = (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
* `webkitmouseforcewillbegin`
* `webkitmouseforcedown`
* `webkitmouseforceup`


Element: ariaModal property - Web APIs

Element: ariaModal property
===========================

The **`ariaModal`** property of the `Element` interface reflects the value of the `aria-modal` attribute, which indicates whether an element is modal when displayed. Applying the `aria-modal` property to an element with `role="dialog"` replaces the technique of using aria-hidden on the background for informing assistive technologies that content outside a dialog is inert.

Value
-----

A string with one of the following values:

`"true"`

The element is modal.

`"false"`

The element is not modal.

Examples
--------

In this example the `aria-modal` attribute on the element with an ID of `address-modal` is set to "true" indicating that this is a modal dialog. Using `ariaModal` we update the value to "false".

```html
<div
 role="dialog"
 id="address-modal"
 aria-labelledby="dialog1Title"
 aria-describedby="dialog1Desc"
 aria-modal="true"></div>
```

```js
let el = document.getElementById("address-modal");
console.log(el.ariaModal); // "true"
el.ariaModal = "false";
console.log(el.ariaModal); // "false"
```

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

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

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

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

See also
--------

* ARIA: dialog role


Element: toggleAttribute() method - Web APIs

Element: toggleAttribute() method
=================================

 The **`toggleAttribute()`** method of the
 `Element` interface toggles a Boolean attribute (removing it if it is
 present and adding it if it is not present) on the given element.

Syntax
------

```js
toggleAttribute(name)
toggleAttribute(name, force)
```

### Parameters

`name`

 A string specifying the name of the attribute to be toggled. The
 attribute name is automatically converted to all lower-case when
 `toggleAttribute()` is called on an HTML element in an HTML document.

`force` Optional

A boolean value which has the following effects:

* if not specified at all, the `toggleAttribute` method "toggles" the attribute named `name` — removing it if it is present, or else adding it if it is not present
* if true, the `toggleAttribute` method adds an attribute named `name`
* if false, the `toggleAttribute` method removes the attribute named `name`

### Return value

`true` if attribute **`name`** is eventually
 present, and `false` otherwise.

### Exceptions

`InvalidCharacterError` `DOMException`

 The specified attribute `name` contains one or more characters which
 are not valid in attribute names.

Examples
--------

 In the following example, `toggleAttribute()` is used to toggle the
 `disabled` attribute of an `<input>`.

### HTML

```html
<input value="text" /> <button>toggleAttribute("disabled")</button>
```

### JavaScript

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

button.addEventListener("click", () => {
  input.toggleAttribute("disabled");
});
```

### Result

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-toggleattribute① |

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

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


Element: localName property - Web APIs

Element: localName property
===========================

 The **`Element.localName`** read-only property returns the
 local part of the qualified name of an element.

Value
-----

A string representing the local part of the element's qualified name.

Examples
--------

 (Must be served with XML content type, such as `text/xml` or
 `application/xhtml+xml`.)

```xml
<html xmlns="http://www.w3.org/1999/xhtml"
 xmlns:svg="http://www.w3.org/2000/svg">
<head>
  <script type="application/javascript"><![CDATA[
 function test() {
 const text = document.getElementById('text');
 const circle = document.getElementById('circle');

 text.value = "<svg:circle> has:\n" +
 "localName = '" + circle.localName + "'\n" +
 "namespaceURI = '" + circle.namespaceURI + "'";
 }
 ]]></script>
</head>
<body onload="test()">
  <svg:svg version="1.1"
 width="100px" height="100px"
 viewBox="0 0 100 100">
    <svg:circle cx="50" cy="50" r="30" style="fill:#aaa" id="circle"/>
  </svg:svg>
  <textarea id="text" rows="4" cols="55"/>
</body>
</html>
```

Notes
-----

 The local name of a node is that part of the node's qualified name that comes after the
 colon. Qualified names are typically used in XML as part of the namespace(s) of the
 particular XML documents. For example, in the qualified name
 `ecomm:partners`, `partners` is the local name and
 `ecomm` is the prefix:

```xml
<ecomm:business id="soda\_shop" type="brick\_n\_mortar" xmlns:ecomm="http://example.com/ecomm">
  <ecomm:partners>
    <ecomm:partner id="1001">Tony's Syrup Warehouse
    </ecomm:partner>
  </ecomm:partner>
</ecomm:business>
```

**Note:** While the property returns the case of the internal DOM storage, which is lower case, note that `tagName` property returns upper case for HTML elements in HTML DOMs.

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

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

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

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

See also
--------

* `Element.namespaceURI`
* `Element.prefix`
* `Attr.localName`


Element: mouseover event - Web APIs

Element: mouseover event
========================

The **`mouseover`** event is fired at an `Element` when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the element or one of its child elements.

Syntax
------

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

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

onmouseover = (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
--------

The following example illustrates the difference between `mouseover` and `mouseenter` events.

### HTML

```html
<ul id="test">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>
```

### JavaScript

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

// This handler will be executed only once when the cursor
// moves over the unordered list
test.addEventListener(
  "mouseenter",
  (event) => {
    // highlight the mouseenter target
    event.target.style.color = "purple";

    // reset the color after a short delay
    setTimeout(() => {
      event.target.style.color = "";
    }, 500);
  },
  false,
);

// This handler will be executed every time the cursor
// is moved over a different list item
test.addEventListener(
  "mouseover",
  (event) => {
    // highlight the mouseover target
    event.target.style.color = "orange";

    // reset the color after a short delay
    setTimeout(() => {
      event.target.style.color = "";
    }, 500);
  },
  false,
);
```

### Result

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

| Specification |
| --- |
| UI Events # event-type-mouseover |
| HTML Standard # handler-onmouseover |

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: beforematch event - Web APIs

Element: beforematch event
==========================

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

An element receives a **`beforematch`** event when it is in the *hidden until found* state and the browser is about to reveal its content because the user has found the content through the "find in page" feature or through fragment navigation.

Syntax
------

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

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

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

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

A generic `Event`.

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

The HTML `hidden` attribute accepts a value `until-found`: when this value is specified, the element is hidden but its content will be accessible to the browser's "find in page" feature or to fragment navigation. When these features cause a scroll to an element in a "hidden until found" subtree, the browser will:

* fire a `beforematch` event on the hidden element
* remove the `hidden` attribute from the element
* scroll to the element
Examples
--------

### Using beforematch

In this example we have:

* Two `<div>` elements. The first is not hidden, while the second has `hidden="until-found"`and `id="until-found-box"` attributes.
* A link whose target is the `"until-found-box"` fragment.

We also have some JavaScript that listens for the `beforematch` event firing on the hidden until found element. The event handler changes the text content of the box.

#### HTML

```html
<a href="#until-found-box">Go to hidden content</a>

<div>I'm not hidden</div>
<div id="until-found-box" hidden="until-found">Hidden until found</div>
```

```
<button id="reset">Reset</button>
```

#### CSS

```css
div {
  height: 40px;
  width: 300px;
  border: 5px dashed black;
  margin: 1rem 0;
  padding: 1rem;
  font-size: 2rem;
}
```

```
#until-found-box {
  scroll-margin-top: 200px;
}
```

#### JavaScript

```js
const untilFound = document.querySelector("#until-found-box");
untilFound.addEventListener(
  "beforematch",
  () => (untilFound.textContent = "I've been revealed!"),
);
```

```
document.querySelector("#reset").addEventListener("click", () => {
  document.location.hash = "";
  document.location.reload();
});
```

#### Result

Clicking the "Go to hidden content" button navigates to the hidden-until-found element. The `beforematch` event fires, the text content is updated, and then the element's content is displayed.

To run the example again, click "Reload".

If your browser does not support the `"until-found"` enumerated value of the `hidden` attribute, the second `<div>` will be hidden (as `hidden` was boolean prior to the addition of the `until-found` value).

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

| Specification |
| --- |
| HTML Standard # event-beforematch |

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

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

See also
--------

* The HTML `hidden` attribute


Element: getBoundingClientRect() method - Web APIs

Element: getBoundingClientRect() method
=======================================

 The **`Element.getBoundingClientRect()`** method returns a
 `DOMRect` object providing information about the size of an element and its
 position relative to the viewport.

Syntax
------

```js
getBoundingClientRect()
```

### Parameters

None.

### Return value

 The returned value is a `DOMRect` object which is the smallest rectangle
 which contains the entire element, including its padding and border-width. The
 `left`, `top`, `right`, `bottom`,
 `x`, `y`, `width`, and `height` properties
 describe the position and size of the overall rectangle in pixels. Properties other than
 `width` and `height` are relative to the top-left of the viewport.

![DOMRect object that is the smallest rectangle containing the entire element.](/en-US/docs/Web/API/Element/getBoundingClientRect/element-box-diagram.png)

 The `width` and `height` properties of the `DOMRect`
 object returned by the method include the `padding` and
 `border-width`, not only the content width/height. In the standard box model,
 this would be equal to the `width` or `height` property of the
 element + `padding` + `border-width`. But
 if `box-sizing: border-box` is
 set for the element this would be directly equal to its `width` or
 `height`.

 The returned value can be thought of as the union of the rectangles returned by
 `getClientRects()` for the element, i.e., the CSS
 border-boxes associated with the element.

 Empty border-boxes are completely ignored. If all the element's border-boxes are empty,
 then a rectangle is returned with a `width` and `height` of zero
 and where the `top` and `left` are the top-left of the border-box
 for the first CSS box (in content order) for the element.

 The amount of scrolling that has been done of the viewport area (or any other
 scrollable element) is taken into account when computing the bounding rectangle. This
 means that the rectangle's boundary edges (`top`, `right`,
 `bottom`, `left`) change their values every time the scrolling
 position changes (because their values are relative to the viewport and not absolute).

 If you need the bounding rectangle relative to the top-left corner of the document,
 just add the current scrolling position to the `top` and `left`
 properties (these can be obtained using `window.scrollY` and
 `window.scrollX`) to get a bounding rectangle which is independent from the
 current scrolling position.

Examples
--------

### Basic

 This simple example retrieves the `DOMRect` object representing the bounding
 client rect of a simple `<div>` element, and prints out its properties
 below it.

```html
<div></div>
```

```css
div {
  width: 400px;
  height: 200px;
  padding: 20px;
  margin: 50px auto;
  background: purple;
}
```

```js
let elem = document.querySelector("div");
let rect = elem.getBoundingClientRect();
for (const key in rect) {
  if (typeof rect[key] !== "function") {
    let para = document.createElement("p");
    para.textContent = `${key} : ${rect[key]}`;
    document.body.appendChild(para);
  }
}
```

 Notice how the `width`/`height` are equal to its
 `width`/`height` + `padding`.

 Also note how the values of `x`/`left`,
 `y`/`top`, `right`, and `bottom` are equal
 to the absolute distance from the relevant edge of the viewport to that side of the
 element, in each case.

### Scrolling

This example demonstrates how bounding client rect is changing when document is scrolled.

```html
<div id="example"></div>
<div id="controls"></div>
```

```css
div#example {
  width: 400px;
  height: 200px;
  padding: 20px;
  margin: 50px auto;
  background: purple;
}

body {
  padding-bottom: 1000px;
}
p {
  margin: 0;
}
```

```js
function update() {
  const container = document.getElementById("controls");
  const elem = document.getElementById("example");
  const rect = elem.getBoundingClientRect();

  container.innerHTML = "";
  for (const key in rect) {
    if (typeof rect[key] !== "function") {
      let para = document.createElement("p");
      para.textContent = `${key} : ${rect[key]}`;
      container.appendChild(para);
    }
  }
}

document.addEventListener("scroll", update);
update();
```

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

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

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

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

See also
--------

* `getClientRects()`
* MSDN: `getBoundingClientRect`
* MSDN: `ClientRect`, an earlier version of `DOMRect`


Element: scroll() method - Web APIs

Element: scroll() method
========================

 The **`scroll()`** method of the `Element`
 interface scrolls the element to a particular set of coordinates inside a given
 element.

Syntax
------

```js
scroll(x-coord, y-coord)
scroll(options)
```

### Parameters

`x-coord`

 The pixel along the horizontal axis of the element that you want displayed in the
 upper left.

`y-coord`

 The pixel along the vertical axis of the element that you want displayed in the
 upper left.

- or -

`options`

A dictionary containing the following parameters:

`top`

Specifies the number of pixels along the Y axis to scroll the window or element.

`left`

Specifies the number of pixels along the X axis to scroll the window or element.

`behavior`

Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:

* `smooth`: scrolling should animate smoothly
* `instant`: scrolling should happen instantly in a single jump
* `auto`: scroll behavior is determined by the computed value of `scroll-behavior`

### Return value

None (`undefined`).

Examples
--------

```js
// Put the 1000th vertical pixel at the top of the element
element.scroll(0, 1000);
```

Using `options`:

```js
element.scroll({
  top: 100,
  left: 100,
  behavior: "smooth",
});
```

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

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

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

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