HTMLInputElement: stepUp() method - Web APIs

HTMLInputElement: stepUp() method
=================================

 The **`HTMLInputElement.stepUp()`** method increments the value
 of a numeric type of `<input>` element by the value of the
 `step` attribute, or the
 default `step` value if the step attribute is not explicitly set. The method,
 when invoked, increments the `value` by
 (`step` \* n), where `n` defaults to
 `1` if not specified, and
 `step` defaults to the
 default value for `step` if not specified.

| Input type | Default step value | Example step declaration |
| --- | --- | --- |
| date | `1` (day) | 7 day (one week) increments:`<input type="date" min="2019-12-25" step="7">` |
| month | `1` (month) | 12 month (one year) increments:`<input type="month" min="2019-12" step="12">` |
| week | `1` (week) | Two week increments:`<input type="week" min="2019-W23" step="2">` |
| time | `60` (seconds) | 900 second (15 minute) increments:`<input type="time" min="09:00" step="900">` |
| datetime-local | `1` (day) | Same day of the week:`<input type="datetime-local" min="019-12-25T19:30"
step="7">` |
| number | `1` | 0.1 increments`<input type="number" min="0" step="0.1" max="10">` |
| range | `1` | Increments by 2:`<input type="range" min="0" step="2" max="10">` |

 The method, when invoked, changes the form control's value by the value given in the
 `step` attribute, multiplied by the parameter, within the constraints set on
 the form control. The default value for the parameter, if no value is passed, is
 `1`. The method will not cause the value to exceed the
 set `max` value, or defy
 the constraints set by the
 `step` attribute.

 If the value before invoking the `stepUp()` method is invalid—for example,
 if it doesn't match the constraints set by the step attribute—invoking the
 `stepUp()` method will return a value that does match the form controls
 constraints.

 If the form control is non time, date, or numeric in nature, and therefore does not
 support the `step` attribute (see the list of supported input types in the
 table above), or if the step value is set to `any`, an
 `InvalidStateError` exception is thrown.

Syntax
------

```js
stepUp()
stepUp(stepIncrement)
```

### Parameters

`stepIncrement` Optional

A numeric value. If no parameter is passed, `stepIncrement` defaults to `1`.

### Return value

None (`undefined`).

Examples
--------

Click the button in this example to increment the number input type:

### HTML

```html
<p>
  <label for="theNumber">
    Enter a number between 0 and 400 that is divisible by 5:
  </label>
  <input type="number" step="5" id="theNumber" min="0" max="400" />
</p>
<p>
  <label>
    Enter how many values of step you would like to increment by or leave it
    blank:
  </label>
  <input type="number" step="1" id="incrementInput" min="0" max="25" />
</p>
<input type="button" value="Increment" id="theButton" />
```

### JavaScript

```js
/\* make the button call the function \*/
const button = document.getElementById("theButton");
button.addEventListener("click", () => {
  stepOnUp();
});

function stepOnUp() {
  let input = document.getElementById("theNumber");
  let val = document.getElementById("incrementInput").value;

  if (val) {
    /\* increment with a parameter \*/
    input.stepUp(val);
  } else {
    /\* or without a parameter. Try it with 0 \*/
    input.stepUp();
  }
}
```

### CSS

```css
input:invalid {
  border: red solid 3px;
}
```

### Result

 Note if you don't pass a parameter to the `stepUp` method, it defaults to
 `1`. Any other value is a multiplier of the `step` attribute
 value, which in this case is `5`. If you pass `4` as the
 `stepIncrement`, the input will `stepUp` by
 `4 * 5`, or `20`. If the parameter is `0`, the number
 will not be incremented. The stepUp will not allow the input to out of range, in this
 case stopping when it reaches `400`, and rounding down any floats that are
 passed as a parameter.

 Try setting the step increment input to `1.2`. What happens when you invoke the
 method?

 Try setting the value to `4`, which is not valid. What happens when you
 invoke the method?

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

| Specification |
| --- |
| HTML Standard # dom-input-stepup-dev |

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

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

See also
--------

* `<input>`
* `HTMLInputElement`
* `HTMLInputElement.stepDown`
* `step`,
 `min` and
 `max` attributes


HTMLInputElement: multiple property - Web APIs

HTMLInputElement: multiple property
===================================

The **`HTMLInputElement.multiple`** property indicates if an input can have more than one value. Firefox currently only supports `multiple` for `<input type="file">`.

Value
-----

A boolean value.

Examples
--------

```js
// fileInput is a <input type=file multiple>
let fileInput = document.getElementById("myfileinput");

if (fileInput.multiple) {
  // Loop fileInput.files
  for (const file of fileInput.files) {
    // Perform action on one file
  }
  // Only one file available
} else {
  let [file] = fileInput.files;
}
```

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

| Specification |
| --- |
| HTML Standard # dom-input-multiple |

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

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

See also
--------

* FileList
* Bug 523771 - Support <input type=file multiple>


HTMLInputElement: setSelectionRange() method - Web APIs

HTMLInputElement: setSelectionRange() method
============================================

 The **`HTMLInputElement.setSelectionRange()`** method sets the
 start and end positions of the current text selection in an `<input>`
 or `<textarea>` element.

 Optionally, in newer browser versions, you can specify the direction in which selection
 should be considered to have occurred. This lets you indicate, for example, that the
 selection was set by the user clicking and dragging from the end of the selected text
 toward the beginning.

 This method updates the `HTMLInputElement.selectionStart`,
 `selectionEnd`, and `selectionDirection` properties in one call.

 Note that according to the WHATWG forms spec `selectionStart`, `selectionEnd` properties and
 `setSelectionRange` method apply only to inputs of types text, search, URL,
 tel and password. Chrome, starting from version 33, throws an exception while accessing
 those properties and method on the rest of input types. For example, on input of type
 number: "Failed to read the 'selectionStart' property from 'HTMLInputElement': The input
 element's type ('number') does not support selection".

 If you wish to select **all** text of an input element, you can use the HTMLInputElement.select()
 method instead.

Syntax
------

```js
setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)
```

### Parameters

 If `selectionEnd` is less than `selectionStart`, then both are
 treated as the value of `selectionEnd`.

`selectionStart`

 The 0-based index of the first selected character. An index greater than the length
 of the element's value is treated as pointing to the end of the value.

`selectionEnd`

 The 0-based index of the character *after* the last selected character. An
 index greater than the length of the element's value is treated as pointing to the end
 of the value.

`selectionDirection` Optional

 A string indicating the direction in which the selection is considered to have been
 performed. Possible values:

* `"forward"`
* `"backward"`
* `"none"` if the direction is unknown or irrelevant. Default value.

### Return value

None (`undefined`).

Examples
--------

 Click the button in this example to select the third, fourth, and fifth characters in
 the text box ("zil" in the word "Mozilla").

### HTML

```html
<input type="text" id="text-box" size="20" value="Mozilla" />
<button onclick="selectText()">Select text</button>
```

### JavaScript

```js
function selectText() {
  const input = document.getElementById("text-box");
  input.focus();
  input.setSelectionRange(2, 5);
}
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-textarea/input-setselectionrange-dev |

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

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

See also
--------

* `<input>`
* `<textarea>`
* `HTMLInputElement`
* `Selection`


HTMLInputElement: reportValidity() method - Web APIs

HTMLInputElement: reportValidity() method
=========================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`reportValidity()`** method of the `HTMLInputElement` interface performs the same validity checking steps as the `checkValidity()` method. If the value is invalid, this method also fires the `invalid` event on the element, and (if the event isn't canceled) reports the problem to the user.

Syntax
------

```js
reportValidity()
```

### Parameters

None.

### Return value

Returns `true` if the element's value has no validity problems; otherwise, returns `false`.

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

| Specification |
| --- |
| HTML Standard # dom-cva-reportvalidity-dev |

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

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

See also
--------

* checkValidity
* Learn: Client-side form validation
* Guide: Constraint validation


HTMLInputElement: popoverTargetElement property - Web APIs

HTMLInputElement: popoverTargetElement property
===============================================

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 **`popoverTargetElement`** property of the `HTMLInputElement` interface gets and sets the popover element to control via an `<input>` element of `type="button"`.

It is the JavaScript equivalent of the `popovertarget` HTML attribute.

Value
-----

A reference to a popover element in the DOM.

Examples
--------

```js
function supportsPopover() {
  return HTMLElement.prototype.hasOwnProperty("popover");
}

const popover = document.getElementById("mypopover");
const toggleBtn = document.getElementById("toggleBtn");

const popoverSupported = supportsPopover();

if (popoverSupported) {
  popover.popover = "auto";
  toggleBtn.popoverTargetElement = popover;
  toggleBtn.popoverTargetAction = "toggle";
} else {
  console.log("Popover API not supported.");
}
```

### Toggle popover action with an auto popover

 This example shows the basic use of the popover API, setting a `<div>` element as a popover, and then setting it as the `popoverTargetElement` of an `<input>` of `type="button"`.
 The `popover` attribute is set to `"auto"`, so the popover can be closed ("light-dismissed") by clicking outside the popover area.

 First we define an `<input>` that we will use to display and hide the popover, and a `<div>` that will be the popover.
 In this case we don't set the `popovertargetaction` HTML attribute on the `<input>` or the `popover` attribute on the `<div>`, as we will be doing so programmatically.

```html
<input id="toggleBtn" type="button" value="Toggle popover" />
<div id="mypopover">This is popover content!</div>
```

 The JavaScript code first gets a handle to the `<div>` and `<input>` elements.
 It then defines a function to check for popover support.

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

// Check for popover API support.
function supportsPopover() {
  return HTMLElement.prototype.hasOwnProperty("popover");
}
```

 If the popover API is supported the code sets the `<div>` element's `popover` attribute to `"auto"` and makes it the popover target of the toggle button.
 We then set the `popoverTargetAction` of the button to `"toggle"`.
 If the popover API is not supported we change the text content of the `<div>` element to state this, and hide the input element.

```js
if (supportsPopover()) {
  // Set the <div> element to be an auto popover
  popover.popover = "auto";

  // Set the button popover target to be the popover
  toggleBtn.popoverTargetElement = popover;

  // Set that the button toggles popover visibility
  toggleBtn.popoverTargetAction = "toggle";
} else {
  popover.textContent = "Popover API not supported.";
  toggleBtn.hidden = true;
}
```

**Note:** A popover element is hidden by default, but if the API is not supported your element will display "as usual".

 You can try out the example below.
 Show and hide the popover by toggling the button.
 The "auto" popover can also be light dismissed by selecting outside the bounds of the popover text.

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

| Specification |
| --- |
| HTML Standard # dom-popovertargetelement |

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


HTMLInputElement: select event - Web APIs

HTMLInputElement: select event
==============================

The **`select`** event fires when some text has been selected.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### Selection logger

```html
<input value="Try selecting some text in this element." />
<p id="log"></p>
```

```js
function logSelection(event) {
  const log = document.getElementById("log");
  const selection = event.target.value.substring(
    event.target.selectionStart,
    event.target.selectionEnd,
  );
  log.textContent = `You selected: ${selection}`;
}

const input = document.querySelector("input");
input.addEventListener("select", logSelection);
```

### onselect equivalent

You can also set up the event handler using the `onselect` property:

```js
input.onselect = logSelection;
```

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

| Specification |
| --- |
| HTML Standard # event-select |
| HTML Standard # handler-onselect |

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

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


HTMLInputElement: showPicker() method - Web APIs

HTMLInputElement: showPicker() method
=====================================

The **`HTMLInputElement.showPicker()`** method displays the browser picker for an `input` element.

This is the same picker that would normally be displayed when the element is selected, but can be triggered from a button press or other user interaction.

 Commonly browsers implement it for inputs of these types: `"date"`, `"month"`, `"week"`, `"time"`, `"datetime-local"`, `"color"`, or `"file"`.
 It can also be prepopulated with items from a `<datalist>` element or `autocomplete` attribute.

More generally, this method should ideally display the picker for any input element on the platform that has a picker.

Syntax
------

```js
showPicker()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the element is not mutable, meaning that the user cannot modify it and/or that it cannot be automatically prefilled.

`NotAllowedError` `DOMException`

Thrown if not explicitly triggered by a user action such as a touch gesture or mouse click (the picker requires Transient activation).

`SecurityError` `DOMException`

Thrown if called in a cross-origin iframe, except for file and color pickers (exempt for historical reasons).

Security
--------

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

Examples
--------

### Feature Detection

The code below shows how to check if `showPicker()` is supported:

```js
if ("showPicker" in HTMLInputElement.prototype) {
  // showPicker() is supported.
}
```

### Normal input pickers

This example shows how this feature can be used for `color` and `file` input pickers.

**Note:** Pickers for `date`, `datetime-local`, `month`, `time`, `week` are launched in the same way.
 They cannot be shown here because live examples run in a cross-origin frame, and would cause a `SecurityError`

#### HTML

```html
<p>
  <input type="color" />
  <button id="color">Show the color picker</button>
</p>

<p>
  <input type="file" />
  <button id="file">Show the file picker</button>
</p>
```

#### JavaScript

The code simply gets the previous element of the selected button and calls `showPicker()` on it.

```js
document.querySelectorAll("button").forEach((button) => {
  button.addEventListener("click", (event) => {
    const input = event.srcElement.previousElementSibling;
    try {
      input.showPicker();
    } catch (error) {
      window.alert(error);
    }
  });
});
```

#### Result

Click the button next to each input type to show its picker.

### showPicker() for a datalist input

`showPicker()` can launch the picker for a list of options defined in a `<datalist>`.

First we define a `<datalist>` in HTML consisting of a number of internet browsers, an input of type `text` that uses it, and a button.

```html
<datalist id="browsers">
  <option value="Chrome"></option>
  <option value="Firefox"></option>
  <option value="Opera"></option>
  <option value="Safari"></option>
  <option value="Microsoft Edge"></option>
</datalist>

<input type="text" list="browsers" />
<button>Select browser</button>
```

The code below adds an event listener that calls `showPicker()` when the button is clicked.

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

button.addEventListener("click", () => {
  try {
    browserInput.showPicker();
  } catch (error) {
    // Fall back to another picker mechanism
  }
});
```

### showPicker() for autocomplete

`showPicker()` can launch a picker for an `autocomplete` input.

Here we define an input that takes an autocomplete option of "name".

```html
<input autocomplete="name" /> <button>Show autocomplete options</button>
```

The code below shows the picker for the input when the button is clicked.

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

button.addEventListener("click", () => {
  try {
    browserInput.showPicker();
  } catch (error) {
    // Fall back to another picker mechanism
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-input-showpicker |

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

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

See also
--------

* `<input>`
* `HTMLInputElement`
* `HTMLSelectElement.showPicker()`
* `<datalist>`
* `autocomplete`


HTMLInputElement: popoverTargetAction property - Web APIs

HTMLInputElement: popoverTargetAction property
==============================================

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 **`popoverTargetAction`** property of the `HTMLInputElement` interface gets and sets the action to be performed (`"hide"`, `"show"`, or `"toggle"`) on a popover element being controlled by an `<input>` element of `type="button"`.

It reflects the value of the `popovertargetaction` HTML attribute.

Value
-----

An enumerated value. Possible values are:

`"hide"`

The button will hide a shown popover. If you try to hide an already hidden popover, no action will be taken.

`"show"`

The button will show a hidden popover. If you try to show an already showing popover, no action will be taken.

`"toggle"`

The button will toggle a popover between showing and hidden. If the popover is hidden, it will be shown; if the popover is showing, it will be hidden. If `popoverTargetAction` is not set, `"toggle"` is the default action that will be performed by the control button.

Examples
--------

### Toggle popover action with an auto popover

 This example shows the basic use of the popover API with a "toggle" value set for the `popoverTargetAction` property.
 The `popover` attribute is set to `"auto"`, so the popover can be closed ("light-dismissed") by clicking outside the popover area.

 First we define an `<input>` of `type="button"` that we will use to show and hide the popover, and a `<div>` that will be the popover.
 In this case we don't set the `popovertargetaction` HTML attribute on the button or the `popover` attribute on the `<div>`, as we will be doing so programmatically.

```html
<input id="toggleBtn" type="button" value="Toggle popover" />
<div id="mypopover">This is popover content!</div>
```

 The JavaScript code first gets a handle to the `<div>` and `<input>` elements.
 It then defines a function to check for popover support.

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

// Check for popover API support.
function supportsPopover() {
  return HTMLElement.prototype.hasOwnProperty("popover");
}
```

 If the popover API is supported the code sets the `<div>` element's `popover` attribute to `"auto"` and makes it the popover target of the toggle button.
 We then set the `popoverTargetAction` of the button to `"toggle"`.
 If the popover API is not supported we change the text content of the `<div>` element to state this, and hide the toggle button.

```js
if (supportsPopover()) {
  // Set the <div> element to be an auto popover
  popover.popover = "auto";
  // Set the button popover target to be the popover
  toggleBtn.popoverTargetElement = popover;

  // Set that the button toggles popover visibility
  toggleBtn.popoverTargetAction = "toggle";
} else {
  popover.textContent = "Popover API not supported.";
  toggleBtn.hidden = true;
}
```

**Note:** A popover element is hidden by default, but if the API is not supported your element will display "as usual".

 You can try out the example below.
 Show and hide the popover by toggling the button.
 The "auto" popover can also be dismissed by selecting outside the bounds of the popover text.

### Show/hide popover action with a manual popover

This example shows how to use the `"show"` and `"hide"` values of the `popoverTargetAction` attribute.

 The code is near identical to the previous example, except that there are two `<button>` elements, and the popover is set to `"manual"`.
 A `manual` popover must be closed explicitly, and not "light dismissed" by selecting outside the popover area.

```html
<input id="showBtn" type="button" value="Show popover" />
<input id="hideBtn" type="button" value="Hide popover" />
<div id="mypopover">This is popover content!</div>
```

```js
function supportsPopover() {
  return HTMLElement.prototype.hasOwnProperty("popover");
}

const popover = document.getElementById("mypopover");
const showBtn = document.getElementById("showBtn");
const hideBtn = document.getElementById("hideBtn");

const popoverSupported = supportsPopover();

if (supportsPopover()) {
  // Set the <div> element be a manual popover
  popover.popover = "manual";

  // Set the button targets to be the popover
  showBtn.popoverTargetElement = popover;
  hideBtn.popoverTargetElement = popover;

  // Set the target actions to be show/hide
  showBtn.popoverTargetAction = "show";
  hideBtn.popoverTargetAction = "hide";
} else {
  popover.textContent = "Popover API not supported.";
  showBtn.hidden = true;
  hideBtn.hidden = true;
}
```

The popover can be displayed by selecting the "Show popover" button, and dismissed using the "Hide popover" button.

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

| Specification |
| --- |
| HTML Standard # dom-popovertargetaction |

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


HTMLInputElement: invalid event - Web APIs

HTMLInputElement: invalid event
===============================

The **`invalid`** event fires when a submittable element has been checked for validity and doesn't satisfy its constraints.

This event can be useful for displaying a summary of the problems with a form on submission. When a form is submitted, `invalid` events are fired at each form control that is invalid. The validity of submittable elements is checked before submitting their owner `<form>`, or after the `checkValidity()` method of the element or its owner `<form>` is called.

It is not checked on `blur`.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

If a form is submitted with an invalid value, the submittable elements are checked and, if an error is found, the `invalid` event will fire on the `invalid` element. In this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged.

### HTML

```html
<form action="#">
  <div>
    <label>
      Enter an integer between 1 and 10:
      <input type="number" min="1" max="10" required />
    </label>
  </div>
  <div><input type="submit" value="submit" /></div>
</form>
<hr />
Invalid values:
<ul id="log"></ul>
```

### JavaScript

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

input.addEventListener("invalid", (e) => {
  log.appendChild(
    Object.assign(document.createElement("li"), {
      textContent: JSON.stringify(e.target.value),
    }),
  );
});
```

### Result

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

| Specification |
| --- |
| HTML Standard # event-invalid |

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

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

See also
--------

* HTML `<form>` element
* Related event: `submit`
* CSS `:invalid` pseudo class


HTMLInputElement: webkitdirectory property - Web APIs

HTMLInputElement: webkitdirectory property
==========================================

 The **`HTMLInputElement.webkitdirectory`** is a property
 that reflects the `webkitdirectory` HTML attribute
 and indicates that the `<input>` element should let the user select directories instead of files.
 When a directory is selected, the directory and its entire hierarchy of contents are included in the set of selected items.
 The selected file system entries can be obtained using the `webkitEntries` property.

**Note:** This property is called `webkitEntries` in the specification due to its
 origins as a Google Chrome-specific API. It's likely to be renamed someday.

Value
-----

 A Boolean; `true` if the `<input>` element should allow
 picking only directories or `false` if only files should be selectable.

Understanding the results
-------------------------

 After the user makes a selection, each `File` object in `files`
 has its `File.webkitRelativePath` property set to the relative path within
 the selected directory at which the file is located. For example, consider this file
 system:

* PhotoAlbums
    + Birthdays
        - Jamie's 1st birthday
            * PIC1000.jpg
            * PIC1004.jpg
            * PIC1044.jpg
        - Don's 40th birthday
            * PIC2343.jpg
            * PIC2344.jpg
            * PIC2355.jpg
            * PIC2356.jpg
    + Vacations
        - Mars
            * PIC5533.jpg
            * PIC5534.jpg
            * PIC5556.jpg
            * PIC5684.jpg
            * PIC5712.jpg

 If the user chooses `PhotoAlbums`, then the list reported by files will
 contain `File` objects for every file listed above—but not the directories.
 The entry for `PIC2343.jpg` will have a `webkitRelativePath` of
 `PhotoAlbums/Birthdays/Don's 40th birthday/PIC2343.jpg`. This makes it
 possible to know the hierarchy even though the `FileList` is flat.

**Note:** The behavior of `webkitRelativePath` is different
 in *Chromium < 72*. See this bug for
 further details.

Examples
--------

 In this example, a directory picker is presented which lets the user choose one or more
 directories. When the `change` event occurs, a list of all files contained
 within the selected directory hierarchies is generated and displayed.

### HTML

```html
<input type="file" id="filepicker" name="fileList" webkitdirectory multiple />
<ul id="listing"></ul>
```

### JavaScript

```js
document.getElementById("filepicker").addEventListener(
  "change",
  (event) => {
    let output = document.getElementById("listing");
    for (const file of event.target.files) {
      let item = document.createElement("li");
      item.textContent = file.webkitRelativePath;
      output.appendChild(item);
    }
  },
  false,
);
```

### Result

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

| Specification |
| --- |
| File and Directory Entries API # dom-htmlinputelement-webkitdirectory |

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

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

See also
--------

* File and Directory Entries API
* `HTMLInputElement.webkitEntries`
* `File.webkitRelativePath`


HTMLInputElement: search event - Web APIs

HTMLInputElement: search 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 **`search`** event is fired when a search is initiated using an `<input>` element of `type="search"`.

There are several ways a search can be initiated, such as by pressing `Enter` while the `<input>` is focused, or, if the `incremental` attribute is present, after a UA-defined timeout elapses since the most recent keystroke (with new keystrokes resetting the timeout so the firing of the event is debounced).

Current UA implementations of `<input type="search">` have an additional control to clear the field. Using this control also fires the `search` event. In that case the `value` of the `<input>` element will be the empty string.

This event is not cancelable.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
// addEventListener version
const input = document.querySelector('input[type="search"]');

input.addEventListener("search", () => {
  console.log(`The term searched for was ${input.value}`);
});
```

```js
// onsearch version
const input = document.querySelector('input[type="search"]');

input.onsearch = () => {
  console.log(`The term searched for was ${input.value}`);
};
```

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

This event is not part of any specification.

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

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


HTMLInputElement: select() method - Web APIs

HTMLInputElement: select() method
=================================

 The **`HTMLInputElement.select()`** method selects all the text
 in a `<textarea>` element or in an `<input>` element
 that includes a text field.

Syntax
------

```js
select()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

 Click the button in this example to select all the text in the
 `<input>` element.

### HTML

```html
<input type="text" id="text-box" size="20" value="Hello world!" />
<button onclick="selectText()">Select text</button>
```

### JavaScript

```js
function selectText() {
  const input = document.getElementById("text-box");
  input.focus();
  input.select();
}
```

### Result

Notes
-----

 Calling `element.select()` will not necessarily focus the input, so it is
 often used with `HTMLElement.focus`.

 In browsers where it is not supported, it is possible to replace it with a call to HTMLInputElement.setSelectionRange() with
 parameters 0 and the input's value length:

```html
<input onClick="this.select();" value="Sample Text" />
<!-- equivalent to -->
<input
 onClick="this.setSelectionRange(0, this.value.length);"
 value="Sample Text" />
```

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

| Specification |
| --- |
| HTML Standard # dom-textarea/input-select |

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

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

See also
--------

* `<input>`
* `<textarea>`
* `HTMLInputElement`
* `HTMLInputElement.setSelectionRange`


HTMLInputElement: setCustomValidity() method - Web APIs

HTMLInputElement: setCustomValidity() method
============================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`HTMLInputElement.setCustomValidity()`** method sets a custom validity message for the element.

Syntax
------

```js
setCustomValidity(message)
```

### Parameters

`message`

The message to use for validity errors.

### Return value

None (`undefined`).

### Exceptions

None.

Examples
--------

 In this example, we pass the ID of an input element, and set different error messages
 depending on whether the value is missing, too low, or too high. Additionally you
 *must* call the `reportValidity()`
 method on the same element or else nothing will happen.

```js
function validate(inputID) {
  const input = document.getElementById(inputID);
  const validityState = input.validity;

  if (validityState.valueMissing) {
    input.setCustomValidity("You gotta fill this out, yo!");
  } else if (validityState.rangeUnderflow) {
    input.setCustomValidity("We need a higher number!");
  } else if (validityState.rangeOverflow) {
    input.setCustomValidity("That's too high!");
  } else {
    input.setCustomValidity("");
  }

  input.reportValidity();
}
```

 It's vital to set the message to an empty string if there are no errors. As long as the
 error message is not empty, the form will not pass validation and will not be
 submitted.

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

| Specification |
| --- |
| HTML Standard # dom-cva-setcustomvalidity-dev |

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

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

See also
--------

* Learn: Client-side form validation
* Guide: Constraint validation
* `ValidityState`


HTMLInputElement: labels property - Web APIs

HTMLInputElement: labels property
=================================

 The **`HTMLInputElement.labels`** read-only property returns a
 `NodeList` of the `<label>` elements associated with the
 `<input>` element, if the element is not hidden. If the element has the
 type `hidden`, the property returns `null`.

Value
-----

 A `NodeList` containing the `<label>` elements associated
 with the `<input>` element.

Examples
--------

### HTML

```html
<label id="label1" for="test">Label 1</label>
<input id="test" />
<label id="label2" for="test">Label 2</label>
```

### JavaScript

```js
window.addEventListener("DOMContentLoaded", () => {
  const input = document.getElementById("test");
  for (const label of input.labels) {
    console.log(label.textContent); // "Label 1" and "Label 2"
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-lfe-labels-dev |

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

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


HTMLInputElement: disabled property - Web APIs

HTMLInputElement: disabled property
===================================

The **`HTMLInputElement.disabled`** property is a boolean value that reflects the `disabled` HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks. A disabled element is unusable and un-clickable.

Value
-----

A boolean value.

Examples
--------

### HTML

```html
<p>
  <label>
    <input id="check-box" name="b" value="1" type="checkbox" disabled /> Check
    this box!
  </label>
</p>
<p>
  <label>
    <input id="toggle-box" name="b" value="2" type="checkbox" /> Enable the
    other checkbox.
  </label>
</p>
```

### JavaScript

```js
const checkBox = document.getElementById("check-box");
const toggleBox = document.getElementById("toggle-box");

toggleBox.addEventListener(
  "change",
  (event) => {
    checkBox.disabled = !event.target.checked;
  },
  false,
);
```

### Result

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

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

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

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


GPUQueue: onSubmittedWorkDone() method - Web APIs

GPUQueue: onSubmittedWorkDone() method
======================================

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

 The **`onSubmittedWorkDone()`** method of the
 `GPUQueue` interface returns a `Promise` that resolves when all the work submitted to the GPU via this `GPUQueue` at the point the method is called has been processed.

This includes the completion of any `mapAsync()` calls made on `GPUBuffer`s used in commands submitted to the queue, before `onSubmittedWorkDone()` is called.

 Note: In most cases, you do *not* need to call `onSubmittedWorkDone()`. You do ***not*** need to call it for mapping a buffer. `mapAsync` guarantees work submitted
 to the queue before calling `mapAsync` happens before the `mapAsync` returns (see WebGPU spec: section 5.2)

The two use cases for `onSubmittedWorkDone`

1. Waiting for multiple buffer mapping (slow)

```js
// good
await Promise.all([
  buffer1.mapAsync(),
  buffer2.mapAsync(),
  buffer3.mapAsync(),
]);
data1 = buffer1.getMappedRange();
data2 = buffer2.getMappedRange();
data3 = buffer3.getMappedRange();
```

```js
// works but slow
buffer1.mapAsync();
buffer2.mapAsync();
buffer3.mapAsync();
await device.queue.onSubmittedWorkDone();
data1 = buffer1.getMappedRange();
data2 = buffer2.getMappedRange();
data3 = buffer3.getMappedRange();
```

The reason the second method is slow is, the implementation may be able to map the buffers before all the submitted work is done.
 For example, if all the buffers are finished being used, but more work (unrelated to the buffers) is already submitted, then
 you'll end up waiting longer using the second method than the first.
2. Throttling work
 If you are doing heavy compute work and you submit too much work at once, the browser may kill your work.
 You can throttle the work by only submitting more work when the work you've already submitted is done.
Syntax
------

```js
device.queue.onSubmittedWorkDone()
```

### Parameters

None.

### Return value

A `Promise` that resolves with `Undefined`.

Examples
--------

```js
device.queue.submit([commandEncoder.finish()]);
device.queue.onSubmittedWorkDone().then(() => {
  console.log("All submitted commands processed.");
});
```

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

| Specification |
| --- |
| WebGPU # dom-gpuqueue-onsubmittedworkdone |

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

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

See also
--------

* The WebGPU API


GPUQueue: submit() method - Web APIs

GPUQueue: submit() method
=========================

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

 The **`submit()`** method of the
 `GPUQueue` interface schedules the execution of command buffers represented by one or more `GPUCommandBuffer` objects by the GPU.

Syntax
------

```js
submit(commandBuffers)
```

### Parameters

`commandBuffers`

An array of `GPUCommandBuffer` objects containing the commands to be enqueued for processing by the GPU.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`submit()`**, otherwise a `GPUValidationError` is generated and the `GPUQueue` becomes invalid:

* Any `GPUBuffer`, `GPUTexture`, and `GPUQuerySet` objects used in the encoded commands are available for use, i.e. not unavailable (`GPUBuffer`s are unavailable if they are currently mapped) or destroyed (with the `destroy()` method).
* Any `GPUExternalTexture` objects used in the encoded commands are not expired (they expire automatically shortly after being imported via `importExternalTexture()`).
* If a `GPUQuerySet` object used in an encoded command is of type `"occlusion"` query, it is not already used, except by `GPURenderPassEncoder.beginOcclusionQuery()`.
Examples
--------

In our basic render demo, a number of commands are recorded via a `GPUCommandEncoder`:

```js
// ...

// Create GPUCommandEncoder
const commandEncoder = device.createCommandEncoder();

// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass

const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// Draw a triangle

passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

// End the render pass

passEncoder.end();

// ...
```

The commands encoded by the `GPUCommandEncoder` are recoded into a `GPUCommandBuffer` using the `GPUCommandEncoder.finish()` method. The command buffer is then passed into the queue via a `submit()` call, ready to be processed by the GPU.

```js
device.queue.submit([commandEncoder.finish()]);
```

**Note:** Study the WebGPU samples to find more queue examples.

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

| Specification |
| --- |
| WebGPU # dom-gpuqueue-submit |

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

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

See also
--------

* The WebGPU API


GPUQueue: copyExternalImageToTexture() method - Web APIs

GPUQueue: copyExternalImageToTexture() method
=============================================

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

 The **`copyExternalImageToTexture()`** method of the
 `GPUQueue` interface copies a snapshot taken from a source image, video, or canvas into a given `GPUTexture`.

Using this function allows the user agent to determine the most efficient way to copy the data over for each source type.

Syntax
------

```js
copyExternalImageToTexture(source, destination, copySize)
```

### Parameters

`source`

An object representing the source to write to the destination, and its origin. This can take the following properties:

`source`

An object providing the source of the snapshot to copy. This can be an `ImageBitmap`, `HTMLVideoElement`, `VideoFrame`, `HTMLCanvasElement`, or `OffscreenCanvas`. The image source data is captured at the exact moment `copyExternalImageToTexture()` is invoked.

`origin` Optional

An object or array specifying the origin of the copy — the top-left corner of the source sub-region to copy from. Together with `copySize`, this defines the full extent of the source sub-region. The `x` and `y` values default to 0 if any of all of `origin` is omitted.

What follows is a sample array:

```js
origin: [0, 0];
```

The object equivalent would look like this:

```js
origin: {
  x: 0,
  y: 0
}
```

`flipY` Optional

A boolean. If set to `true`, the image capture is flipped vertically. If omitted, `flipY` defaults to `false`.

`destination`

An object defining the texture subresource and origin to write the captured image to, plus encoding metadata. This can take the following properties:

`aspect` Optional

An enumerated value defining which aspects of the texture to write the image to. Possible values are:

`"all"`

All available aspects of the texture format will be written to, which can mean all or any of color, depth, and stencil, depending on what kind of format you are dealing with.

`"depth-only"`

Only the depth aspect of a depth-or-stencil format will be written to.

`"stencil-only"`

Only the stencil aspect of a depth-or-stencil format will be written to.

If omitted, `aspect` takes a value of `"all"`.

`colorSpace` Optional

An enumerated value describing the color space and encoding used to encode data into the destination texture. Possible values are `"srgb"` and `"display-p3"`. If omitted, `colorSpace` defaults to `"srgb"`.

**Note:** The encoding may result in values outside of the range `[0, 1]` being written to the target texture, if its format can represent them. Otherwise, the results are clamped to the target texture format's range. Conversion may not be necessary if `colorSpace` matches the source image color space.

`mipLevel` Optional

A number representing the mip-map level of the texture to write the image to. If omitted, `mipLevel` defaults to 0.

`origin` Optional

An object or array specifying the origin of the copy — the minimum corner of the texture region to write the image data to. Together with `copySize`, this defines the full extent of the region to copy to. The `x`, `y`, and `z` values default to 0 if any of all of `origin` is omitted.

What follows is a sample array:

```js
origin: [0, 0, 0];
```

The object equivalent would look like this:

```js
origin: {
  x: 0,
  y: 0,
  z: 0
}
```

`premultipliedAlpha` Optional

A boolean. If set to `true`, the image data written into the texture will have its RGB channels premultiplied by the alpha channel. If omitted, `premultipliedAlpha` defaults to `false`.

**Note:** If this option is set to `true` and the `source` is also premultiplied, the source RGB values must be preserved even if they exceed their corresponding alpha values.

`texture`

A `GPUTexture` object representing the texture to write the data to.

`copySize`

An object or array specifying `width`, `height`, and `depthOrArrayLayers` — of the region to copy from/to.

What follows is a sample array:

```js
origin: [16, 1, 1];
```

The object equivalent would look like this:

```js
origin: {
  width: 16,
  height: 1,
  depthOrArrayLayers: 1
}
```

The `width` value has to be included. If the `height` or `depthOrArrayLayers` values are omitted, they default to 1.

### Return value

None (`Undefined`).

### Exceptions

`OperationError` `DOMException`

The method throws an `OperationError` if the following criteria are not met:

* `source.origin.x` + the width of the region to copy to is less than or equal to the width of the source image.
* `source.origin.y` + the height of the region to copy to is less than or equal to the height of the source image.
* `source.origin.z` + the depthOrArrayLayers of the region to copy to is less than or equal to 1.
* `dataOffset` is equal to or smaller than the size of `data`.
* The size of `data` (when converted to bytes, in the case of `TypedArray`s) is a multiple of 4.

`SecurityError` `DOMException`

Thrown if the image source data is cross-origin.

### Validation

The following criteria must be met when calling **`writeTexture()`**, otherwise a `GPUValidationError` is generated and the `GPUQueue` becomes invalid:

* `mipLevel` is less than the destination `GPUTexture.mipLevelCount`.
* `origin.x` is a multiple of the texel block width of the destination `GPUTexture.format`.
* `origin.y` is a multiple of the texel block height of the destination `GPUTexture.format`.
* If the destination `GPUTexture.format` is a depth-or-stencil format, the image capture size is equal to `size`.
* The destination `GPUTexture.usage` includes the `GPUTextureUsage.COPY_DST` and `GPUTextureUsage.RENDER_ATTACHMENT` flags.
* The destination `GPUTexture.dimension` is `"2d"`.
* The destination `GPUTexture.sampleCount` is 1.
* The destination `GPUTexture.format` is one of the following (which support `GPUTextureUsage.RENDER_ATTACHMENT` usage):
    + `"r8unorm"`
    + `"r16float"`
    + `"r32float"`
    + `"rg8unorm"`
    + `"rg16float"`
    + `"rg32float"`
    + `"rgba8unorm"`
    + `"rgba8unorm-srgb"`
    + `"bgra8unorm"`
    + `"bgra8unorm-srgb"`
    + `"rgb10a2unorm"`
    + `"rgba16float"`
    + `"rgba32float"`
* `destination.origin.x` + `copySize.width` is less than or equal to the `destination` `GPUTexture` `width`.
* `destination.origin.y` + `copySize.height` is less than or equal to the `destination` `GPUTexture` `height`.
* `destination.origin.z` + `copySize.depthOrArrayLayers` is less than or equal to the `destination` `GPUTexture` `depthOrArrayLayers`.
* The `destination` `GPUTexture.width` is a multiple of the texel block width of the destination `GPUTexture.format`.
* The `destination` `GPUTexture.height` is a multiple of the texel block height of the destination `GPUTexture.format`.
Examples
--------

In the WebGPU Samples Textured Cube example, the following snippet is used to fetch an image and upload it into a `GPUTexture`:

```js
let cubeTexture: GPUTexture; // TypeScript
{
  const img = document.createElement("img");
  img.src = new URL(
    "../../../assets/img/Di-3d.png",
    import.meta.url
  ).toString();
  await img.decode();
  const imageBitmap = await createImageBitmap(img);

  cubeTexture = device.createTexture({
    size: [imageBitmap.width, imageBitmap.height, 1],
    format: "rgba8unorm",
    usage:
      GPUTextureUsage.TEXTURE\_BINDING |
      GPUTextureUsage.COPY\_DST |
      GPUTextureUsage.RENDER\_ATTACHMENT,
  });

  device.queue.copyExternalImageToTexture(
    { source: imageBitmap },
    { texture: cubeTexture },
    [imageBitmap.width, imageBitmap.height]
  );
}
```

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

| Specification |
| --- |
| WebGPU # dom-gpuqueue-copyexternalimagetotexture |

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

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

See also
--------

* The WebGPU API


GPUQueue: writeTexture() method - Web APIs

GPUQueue: writeTexture() method
===============================

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

 The **`writeTexture()`** method of the
 `GPUQueue` interface writes a provided data source into a given `GPUTexture`.

This is a convenience function, which provides an alternative to setting texture data via buffer mapping and buffer-to-texture copies. It lets the user agent determine the most efficient way to copy the data over.

Syntax
------

```js
writeTexture(destination, data, dataLayout, size)
```

### Parameters

`destination`

An object defining the texture subresource and origin to write the data source to, which can take the following properties:

`aspect` Optional

An enumerated value defining which aspects of the texture to write the data to. Possible values are:

`"all"`

All available aspects of the texture format will be written to, which can mean all or any of color, depth, and stencil, depending on what kind of format you are dealing with.

`"depth-only"`

Only the depth aspect of a depth-or-stencil format will be written to.

`"stencil-only"`

Only the stencil aspect of a depth-or-stencil format will be written to.

If omitted, `aspect` takes a value of `"all"`.

`mipLevel` Optional

A number representing the mip-map level of the texture to write the data to. If omitted, `mipLevel` defaults to 0.

`origin` Optional

An object or array specifying the origin of the copy — the minimum corner of the texture region to write the data to. Together with `size`, this defines the full extent of the region to copy to. The `x`, `y`, and `z` values default to 0 if any of all of `origin` is omitted.

What follows is a sample array:

```js
origin: [0, 0, 0];
```

The object equivalent would look like this:

```js
origin: {
  x: 0,
  y: 0,
  z: 0
}
```

`texture`

A `GPUTexture` object representing the texture to write the data to.

`data`

An object representing the data source to write into the `GPUTexture`. This can be an `ArrayBuffer`, `TypedArray`, or `DataView`.

`dataLayout`

An object that defines the layout of the content contained in `data`. Possible values are:

`offset` Optional

The offset, in bytes, from the beginning of `data` to the start of the image data to be copied. If omitted, `offset` defaults to 0.

`bytesPerRow` Optional

A number representing the stride, in bytes, between the start of each block row (i.e. a row of complete texel blocks) and the subsequent block row. This is required if there are multiple block rows (i.e. the copy height or depth is more than one block).

`rowsPerImage` Optional

The number of block rows per single image of the texture. `bytesPerRow` × `rowsPerImage` will give you the stride, in bytes, between the start of each complete image. This is required if there are multiple images to copy.

`size`

An object or array specifying the extent of the copy — the far corner of the texture region to write the data to. Together with `destination.origin`, this defines the full extent of the region to copy to. See `destination.origin` for examples of the object/array structure.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`writeTexture()`**, otherwise a `GPUValidationError` is generated and the `GPUQueue` becomes invalid:

* `mipLevel` is less than the destination `GPUTexture.mipLevelCount`.
* `origin.x` is a multiple of the texel block width of the destination `GPUTexture.format`.
* `origin.y` is a multiple of the texel block height of the destination `GPUTexture.format`.
* If the destination `GPUTexture.format` is a depth-or-stencil format or `GPUTexture.sampleCount` is more than 1, the subresource size is equal to `size`.
* The destination `GPUTexture.usage` includes the `GPUTextureUsage.COPY_DST` flag.
* The destination `GPUTexture.sampleCount` is 1.
* `destination.origin.x` + the `destination` `GPUTexture.width` is less than or equal to the width of the subresource to write to the `destination` `GPUTexture`.
* `destination.origin.y` + the `destination` `GPUTexture.height` is less than or equal to the height of the subresource to write to the `destination` `GPUTexture`.
* `destination.origin.z` + the `destination` `GPUTexture.depthOrArrayLayers` is less than or equal to the depthOrArrayLayers of the subresource to write to the `destination` `GPUTexture`.
* The `destination` `GPUTexture.width` is a multiple of the texel block width of the destination `GPUTexture.format`.
* The `destination` `GPUTexture.height` is a multiple of the texel block height of the destination `GPUTexture.format`.
* `destination.aspect` refers to a single aspect of the destination `GPUTexture.format`.
* That aspect is a valid image copy destination according to depth-or-stencil formats.
* The `destination` is otherwise compatible with the `GPUTexture.format`.
Examples
--------

In Efficiently rendering glTF models, a function is defined for creating a solid color texture:

```js
function createSolidColorTexture(r, g, b, a) {
  const data = new Uint8Array([r \* 255, g \* 255, b \* 255, a \* 255]);
  const texture = device.createTexture({
    size: { width: 1, height: 1 },
    format: "rgba8unorm",
    usage: GPUTextureUsage.TEXTURE\_BINDING | GPUTextureUsage.COPY\_DST,
  });
  device.queue.writeTexture({ texture }, data, {}, { width: 1, height: 1 });
  return texture;
}
```

This can be used to define standard textures for use in material libraries:

```js
const opaqueWhiteTexture = createSolidColorTexture(1, 1, 1, 1);
const transparentBlackTexture = createSolidColorTexture(0, 0, 0, 0);
const defaultNormalTexture = createSolidColorTexture(0.5, 0.5, 1, 1);
```

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

| Specification |
| --- |
| WebGPU # dom-gpuqueue-writetexture |

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

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

See also
--------

* The WebGPU API


GPUQueue: writeBuffer() method - Web APIs

GPUQueue: writeBuffer() method
==============================

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

 The **`writeBuffer()`** method of the
 `GPUQueue` interface writes a provided data source into a given `GPUBuffer`.

This is a convenience function, which provides an alternative to setting buffer data via buffer mapping and buffer-to-buffer copies. It lets the user agent determine the most efficient way to copy the data over.

Syntax
------

```js
writeBuffer(buffer, bufferOffset, data, dataOffset, size)
```

### Parameters

`buffer`

A `GPUBuffer` object representing the buffer to write data to.

`bufferOffset`

A number representing the offset, in bytes, to start writing the data at inside the `GPUBuffer`.

`data`

An object representing the data source to write into the `GPUBuffer`. This can be an `ArrayBuffer`, `TypedArray`, or `DataView`.

`dataOffset` Optional

A number representing the offset to start writing the data from inside the data source. This value is a number of elements if `data` is a `TypedArray`, and a number of bytes if not. If omitted, `dataOffset` defaults to 0.

`size` Optional

A number representing the size of the content to write from `data` to `buffer`. This value is a number of elements if `data` is a `TypedArray`, and a number of bytes if not. If omitted, `size` will be equal to the overall size of `data`, minus `dataOffset`.

### Return value

None (`Undefined`).

### Exceptions

`OperationError` `DOMException`

The method throws an `OperationError` if the following criteria are not met:

* The size of `data` is equal to or greater than 0.
* `dataOffset` is equal to or smaller than the size of `data`.
* The size of `data` (when converted to bytes, in the case of `TypedArray`s) is a multiple of 4.

### Validation

The following criteria must be met when calling **`writeBuffer()`**, otherwise a `GPUValidationError` is generated and the `GPUQueue` becomes invalid:

* `buffer` is available for use, i.e. not unavailable (`GPUBuffer`s are unavailable if they are currently mapped) or destroyed (with the `GPUBuffer.destroy()` method).
* The `buffer`'s `GPUBuffer.usage` includes the `GPUBufferUsage.COPY_DST` flag.
* `bufferOffset`, when converted to bytes, is a multiple of 4.
* The size of `data` - `dataOffset` + `bufferOffset`, when converted to bytes, is equal to or less than the `buffer`'s `GPUBuffer.size`.
Examples
--------

In our basic render demo, we define some vertex data in a `Float32Array` that we'll use to draw a triangle:

```js
const vertices = new Float32Array([
  0.0, 0.6, 0, 1, 1, 0, 0, 1, -0.5, -0.6, 0, 1, 0, 1, 0, 1, 0.5, -0.6, 0, 1, 0,
  0, 1, 1,
]);
```

To use this data in a render pipeline, we need to put it into a `GPUBuffer`. First we'll create the buffer:

```js
const vertexBuffer = device.createBuffer({
  size: vertices.byteLength, // make it big enough to store vertices in
  usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY\_DST,
});
```

To get the data into the buffer we can use `writeBuffer()`:

```js
device.queue.writeBuffer(vertexBuffer, 0, vertices, 0, vertices.length);
```

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

| Specification |
| --- |
| WebGPU # dom-gpuqueue-writebuffer |

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

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

See also
--------

* The WebGPU API


GPUQueue: label property - Web APIs

GPUQueue: label property
========================

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

 The **`label`** read-only property of the
 `GPUQueue` interface is a string providing a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

You can get and set it directly on the `GPUQueue` object.

Value
-----

A string. If no label value has previously been set, getting the label returns an empty string.

Examples
--------

Setting and getting a label via `GPUQueue.label`:

```js
device.queue.label = "myqueue";
console.log(device.queue.label); // "myqueue"
```

You can also set the queue's label at the time you request the device, like this:

```js
const device = adapter.requestDevice({
  defaultQueue: { label: "myqueue" },
});
```

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

| Specification |
| --- |
| WebGPU # dom-gpuobjectbase-label |

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

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

See also
--------

* The WebGPU API


RTCRemoteOutboundRtpStreamStats: codecId property - Web APIs

RTCRemoteOutboundRtpStreamStats: codecId property
=================================================

The **`codecId`** property of the `RTCRemoteOutboundRtpStreamStats` dictionary is a string that uniquely identifies the object that was inspected to produce the data in the `RTCCodecStats` for the RTP stream.

Value
-----

A string which uniquely identifies the object from which the contents of the stream's `RTCCodecStats` are derived.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcrtpstreamstats-codecid |

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

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


RTCRemoteOutboundRtpStreamStats: transportId property - Web APIs

RTCRemoteOutboundRtpStreamStats: transportId property
=====================================================

The **`transportId`** property of the `RTCRemoteOutboundRtpStreamStats` dictionary is a string that uniquely identifies the object from which the statistics contained in the `RTCTransportStats` properties in the `RTCStatsReport`.

Value
-----

A string uniquely identifying the source of the statistics contained the `RTCTransportStats` properties in the `RTCStatsReport`.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcrtpstreamstats-transportid |

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

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


RTCRemoteOutboundRtpStreamStats: timestamp property - Web APIs

RTCRemoteOutboundRtpStreamStats: timestamp property
===================================================

The **`timestamp`** property of the `RTCRemoteOutboundRtpStreamStats` dictionary is a `DOMHighResTimeStamp` object specifying the time at which the data in the object was sampled.

Value
-----

A `DOMHighResTimeStamp` value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC.

The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of fingerprinting protection in the form of reduced clock precision or accuracy.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-timestamp |

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

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


RTCRemoteOutboundRtpStreamStats: type property - Web APIs

RTCRemoteOutboundRtpStreamStats: type property
==============================================

The **`type`** property of the `RTCRemoteOutboundRtpStreamStats` dictionary is a string with the value `"remote-outbound-rtp"`.

 Different statistics are obtained by iterating the `RTCStatsReport` object returned by a call to `RTCPeerConnection.getStats()`.
 The type indicates the set of statistics available through the object in a particular iteration step.
 A value of `"remote-outbound-rtp"` indicates that the statistics available in the current step are those defined in `RTCRemoteOutboundRtpStreamStats`.

Value
-----

A string with the value `"remote-outbound-rtp"`.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-type |

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

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


RTCRemoteOutboundRtpStreamStats: localId property - Web APIs

RTCRemoteOutboundRtpStreamStats: localId property
=================================================

The `RTCRemoteOutboundRtpStreamStats` dictionary's **`localId`** property is a string which can be used to identify the `RTCInboundRtpStreamStats` object whose `remoteId` matches this value.

Together, these two objects provide statistics about the inbound and outbound sides of the same synchronization source (SSRC).

Value
-----

A string which can be compared to the value of an `RTCInboundRtpStreamStats` object's `remoteId` property to see if the two represent statistics for each of the two sides of the same set of data received by the local peer.

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

 You can think of the local and remote views of the same RTP stream as pairs, each of which has a reference back to the other one.
 Thus, if an `RTCStatsReport` includes an `remote-outbound-rtp` statistics object (of type `RTCRemoteOutboundRtpStreamStats`), it should also have a corresponding `inbound-rtp` object.
 Both of these provide information about the same batch of packets being transmitted from the remote peer to the local device.
 The difference is
 that `remote-outbound-rtp` describes statistics about the transmission(s) from the perspective of the remote peer, while `inbound-rtp` offers statistics about the incoming data from the local peer's perspective.

You can examine, try out, and experiment with this example on Glitch.

Examples
--------

 In this example, we have a pair of functions: the first, `networkTestStart()`, captures an initial report, and the second, `networkTestStop()`, captures a second report.
 The second function uses the two reports to output some information about the network conditions.

### networkTestStart()

This function calls the `RTCPeerConnection` method `getStats()` to request an `RTCStatsReport` and store it in the variable `startReport`.

```js
let startReport;

async function networkTestStart(pc) {
  if (pc) {
    startReport = await pc.getStats();
  }
}
```

Given an `RTCPeerConnection`, `pc`, this calls its `getStats()` method to obtain a statistics report object, which it stores in `startReport` for use once the end-of-test data has been collected by `networkTestStop()`.

### networkTestStop()

The `networkTestStop()` function obtains a second report, `endReport`, then computes and outputs the results.

#### Finding paired statistics

 Each statistics record of `type` `remote-outbound-rtp` (describing a remote peer's statistics about sending data to the local peer) has a corresponding record of type `inbound-rtp` which describes the local peer's perspective on the same data being moved between the two peers.
 Let's create a utility function to help us look up the value of a key in the paired statistics object.

 The `findReportEntry()` function shown below examines an `RTCStatsReport`, returning the `RTCStatsReport`-based statistics record which contains the specified `key` — *and* for which the key has the specified `value`.
 If no match is found or the statistics report has no record corresponding to the statistics category indicated by `key`.

```js
function findReportEntry(report, key, value) {
  for (const stats of report.values()) {
    if (stats[key] === value) {
      return stats;
    }
  }
  return null;
}
```

 Since the `RTCStatsReport` is a JavaScript `Map`, we can iterate over the map's `values()` to examine each of the `RTCStats`-based statistics records in the report until we find one that has the `key` property with the specified `value`.
 When a match is found, the statistics object is returned.

If no match is found, the function returns `null`.

#### The main networkTestStop() function

Now let's look at the `networkTestStop()` function itself. It takes as input the `RTCPeerConnection` being tested, calls `getStats()` to get a new `RTCStatsReport` with current statistics, then computes the results it's looking for, outputting those results as appropriate to the user by appending appropriate HTML to the contents of the `<div>` element whose class is `stats-box`.

```js
async function networkTestStop(pc) {
  if (pc) {
    const statsBox = document.querySelector(".stats-box");
    const endReport = await pc.getStats();

    for (const endRemoteOutbound of endReport.values()) {
      if (endRemoteOutbound.type === "remote-outbound-rtp") {
        const startRemoteOutbound = startReport.get(endRemoteOutbound.id);

        if (startRemoteOutbound) {
          const startInboundStats = findReportEntry(
            startReport,
            "remoteId",
            startRemoteOutbound.id,
          );
          const endInboundStats = findReportEntry(
            endReport,
            "remoteId",
            endRemoteOutbound.id,
          );
          // Elapsed time in seconds
          const elapsedTime =
            (endRemoteOutbound.timestamp - startRemoteOutbound.timestamp) /
            1000;
          const packetsSent =
            endRemoteOutbound.packetsSent - startRemoteOutbound.packetsSent;
          const bytesSent =
            endRemoteOutbound.bytesSent - startRemoteOutbound.bytesSent;
          const framesDecoded =
            endInboundStats.framesDecoded - startInboundStats.framesDecoded;
          const frameRate = framesDecoded / elapsedTime;

          let timeString = "";
          if (!isNaN(elapsedTime)) {
            timeString = ` representing ${elapsedTime}s`;
          }

          let frameString = "";
          if (!isNaN(framesDecoded)) {
            frameString = `Decoded ${framesDecoded} frames for a frame rate of ${frameRate.toFixed(
 2,
 )} FPS.<br>`;
          }

          const logEntry =
            `<div class="stats-entry"><h2>Report ID: ${endRemoteOutbound.id}</h2>` +
            `Remote peer sent ${packetsSent} packets ${timeString}.<br>` +
            `${frameString}` +
            `Data size: ${bytesSent} bytes.</div>`;
          statsBox.innerHTML += logEntry;
        } else {
          statsBox.innerHTML += `<div class="stats-error">Unable to find initial statistics for ID ${endRemoteOutbound.id}.</div>`;
        }
      }

      statsBox.scrollTo(0, statsBox.scrollHeight);
    }
  }
}
```

 Here's what's going on in the `networkTestStop()` function: after calling the `RTCPeerConnection` method `getStats()` to get the latest statistics report for the connection and storing it in `endReport`.
 This is an `RTCStatsReport` object, which maps strings to objects of the corresponding `RTCStatsReport`-based type.

 Now we can begin to process the results, starting with the ending statistics found in `endReport`.
 In this case, we're looking for statistics records whose `type` is `remote-outbound-rtp`, so we iterate over the entries in the statistics report until we find an entry of that type.
 This object is, specifically, of type `RTCRemoteOutboundRtpStreamStats`, and it provides statistics giving details about the state of things *from the perspective of the remote peer*.
 This statistics record is stored in `endRemoteOutbound`.

 Once the ending `remote-outbound-rtp` record is found, we use its `id` property to get its ID.
 With that in hand, we can look up the `remote-outbound-rtp` record in the starting statistics record (`startReport`), which we store into `startRemoteOutbound`.

 Now we obtain the `inbound-rtp` statistics that correspond to these two `remote-outbound-rtp` records by finding the `remoteId` property within them whose value is the ID of the `remote-outbound-rtp` record.
 We use the `findReportEntry()` function described in the previous section for that, storing the located `inbound-rtp` records in `startInboundStats` and `endInboundStats`.

Now we have all the raw statistics needed to calculate the information we want to display, so we do so:

* We calculate the amount of time—`elapsedTime`—that elapsed between the two reports being sent by subtracting the `timestamp` `startReport` from that of `endReport`.
 We then divide by 1000 to convert the result from milliseconds to seconds.
* We compute the number of packets sent during this interval—`packetsSent`—by subtracting the two reports' values for the `packetsSent` property.
* Similarly, the number of bytes sent during this interval—`bytesSent`—is calculated by subtracting the starting statistics object's `bytesSent` property from that of the ending statistics.
* The number of frames decoded during this interval—`framesDecoded`—is determined by subtracting `startRecord`'s `framesDecoded` from `endRecord.framesDecoded`.
* Finally, the frame rate over the elapsed time span is calculated by dividing `framesDecoded` by `elapsedTime`.

The remainder of the `networkTestStop()` function constructs the HTML used to display the output of the collected and computed results to the user, then append it to the element `statsBox`, which we're using to show the status updates to the user.

The output log, given the styles used by the example, looks like this:

![A screenshot of the example showing logged statistics taken from paired remote-outbound-rtp and inbound-rtp statistics records](/en-US/docs/Web/API/RTCRemoteOutboundRtpStreamStats/localId/rtc-log-screenshot.png)

 In the screenshot, we see a heading followed by the scrollable `<div>` we refer to as `statsBox`.
 The box contains a number of log entries, the last handful of which are visible.
 Each one represents approximately one second of time (since that's much time we're waiting between calling `networkTestStart()` and `networkTestStop()`).

### Try it and fork it

This example is available on Glitch for you to try out, examine, or remix.

Remix It

View Source

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcremoteoutboundrtpstreamstats-localid |

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

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


RTCRemoteOutboundRtpStreamStats: id property - Web APIs

RTCRemoteOutboundRtpStreamStats: id property
============================================

The **`id`** property of the `RTCRemoteOutboundRtpStreamStats` dictionary is a string that uniquely identifies the object for which this object provides statistics.

Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an `RTCPeerConnection`, or an `RTCDataChannel`.

Value
-----

A string that uniquely identifies the object for which this `RTCRemoteOutboundRtpStreamStats` object provides statistics.

The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-id |

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

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


RTCRemoteOutboundRtpStreamStats: remoteTimestamp property - Web APIs

RTCRemoteOutboundRtpStreamStats: remoteTimestamp property
=========================================================

 The `RTCRemoteOutboundRtpStreamStats` property **`remoteTimestamp`** indicates the timestamp on the remote peer at which these statistics were sent.
 This differs from `timestamp`, which indicates the time at which the statistics were generated or received locally.

Value
-----

 A `DOMHighResTimeStamp` value indicating the timestamp on the remote peer at which it sent these statistics.
 This is different from the value `timestamp`, which gives the time at which the statistics were generated or received by the local peer.

 If this property is present, it comes from the RTCP Sender Report (SR) block, which reflects the clock on the remote peer at the time the message was sent.
 Keep in mind that this means the clock may not be synchronized with the local clock, and that both the current time and the pace at which the clock runs may differ to some extent.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcremoteoutboundrtpstreamstats-remotetimestamp |

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

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


RTCRemoteOutboundRtpStreamStats: ssrc property - Web APIs

RTCRemoteOutboundRtpStreamStats: ssrc property
==============================================

The **`ssrc`** property of the `RTCRemoteOutboundRtpStreamStats` dictionary provides the Synchronization Source (SSRC), an integer which uniquely identifies the source of the RTP packets whose statistics are covered by the `RTCStatsReport` that includes this `RTCRemoteOutboundRtpStreamStats` dictionary.

Value
-----

The Synchronization Source (SSRC) is a 32-bit integer uniquely identifying the source of the RTP packets whose statistics are covered by the `RTCStatsReport` object of which this `RTCRtpStreamStats` object is a component.

 The manner in which these values are generated is not mandated by the specification, although it does make recommendations.
 You should not make any assumptions based on the value of `ssrc` other than that any two objects with the same `ssrc` value refer to the same source.
 See RFC 3550, section 8 for additional information about `ssrc`.

**Note:** The specification includes an example that generates values for `ssrc` using MD5.
 While not part of the standard, exactly, it is a good mechanism that may be used by some browsers; others may use other methods, such as random number generators.
 *Do not* rely upon these values meaning anything other than "these objects are associated with the same source."

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcrtpstreamstats-ssrc |

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

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


RTCRemoteOutboundRtpStreamStats: kind property - Web APIs

RTCRemoteOutboundRtpStreamStats: kind property
==============================================

The **`kind`** property of the `RTCRemoteOutboundRtpStreamStats` dictionary is a string indicating whether the described RTP stream contains audio or video media.

Value
-----

The kinds is always one of:

`"audio"`

The track contains audio media.

`"video"`

The track contains video media.

 This string will always be the same as the one provided by the associated `MediaStreamTrack` object's `kind` property.
 It will also match the statistics object's `RTCCodecStats.codec` property's media type.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcrtpstreamstats-kind |

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

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


SVGRect: x property - Web APIs

SVGRect: x property
===================

The x property describes the horizontal coordinate of the position of the element.

Usage context
-------------

| Name | x |
| --- | --- |
| Value | <length> | <percentage> |
| Initial | 0 |
| Applies to | `<mask>`, 'svg', 'rect', 'image', 'foreignObject' |
| Inherited | no |
| Percentages | refer to the size of the current viewport (see Units) |
| Media | visual |
| Computed value | absolute length or percentage |
| Animatable | yes |

Simple usage
------------

A <coordinate> is a length in the user coordinate system that is the given distance from the origin of the user coordinate system along the relevant axis (the x-axis for X coordinates, the y-axis for Y coordinates). Its syntax is the same as that for <length>.

```html
<svg width="100" height="50" xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="0" width="40" height="40" fill="blue"></rect>
</svg>

<svg width="100" height="50" xmlns="http://www.w3.org/2000/svg">
  <rect x="40" y="0" width="40" height="40" fill="green"></rect>
</svg>
```


PictureInPictureWindow: width property - Web APIs

PictureInPictureWindow: width property
======================================

The read-only **`width`** property of the `PictureInPictureWindow` inbterface returns the width of the floating video window in pixels.

Syntax
------

```js
pictureInPictureWindow.width
```

### Value

An integer value indicating the width of the floating video window in pixels if the Picture-in-Picture window is open. Otherwise, it returns `0`.

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

| Specification |
| --- |
| Picture-in-Picture # ref-for-dom-pictureinpicturewindow-width |

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

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

See also
--------

* Picture-in-Picture API
* `PictureInPictureWindow.height`


PictureInPictureWindow: resize event - Web APIs

PictureInPictureWindow: resize event
====================================

The **`resize`** event fires when the floating video window has been resized.

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("resize", (event) => {});

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

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

A `PictureInPictureEvent`. Inherits from `Event`.

Event

PictureInPictureEventEvent properties
----------------

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

`PictureInPictureEvent.pictureInPictureWindow`

Returns the `PictureInPictureWindow` that is resized.

Examples
--------

### Window size logger

```html
<p>Resize the floating video window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
<video id="video" src="" muted autoplay></video>
```

```js
const video = document.querySelector("#video");
const heightOutput = document.querySelector("#height");
const widthOutput = document.querySelector("#width");

function resize(evt) {
  heightOutput.textContent = evt.target.height;
  widthOutput.textContent = evt.target.width;
}

video.requestPictureInPicture().then((pictureInPictureWindow) => {
  pictureInPictureWindow.onresize = resize;
  // or
  pictureInPictureWindow.addEventListener("resize", resize);
});
```

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

| Specification |
| --- |
| Picture-in-Picture # eventdef-pictureinpicturewindow-resize |
| Picture-in-Picture # dom-pictureinpicturewindow-onresize |

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

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


PictureInPictureWindow: height property - Web APIs

PictureInPictureWindow: height property
=======================================

The read-only **`height`** property of the `PictureInPictureWindow` interface returns the height of the floating video window in pixels.

Syntax
------

```js
pictureInPictureWindow.height
```

### Value

An integer value indicating the height of the floating video window in pixels if the Picture-in-Picture window is open. Otherwise, it returns `0`.

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

| Specification |
| --- |
| Picture-in-Picture # ref-for-dom-pictureinpicturewindow-height |

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

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

See also
--------

* Picture-in-Picture API
* `PictureInPictureWindow.width`


PushManager: getSubscription() method - Web APIs

PushManager: getSubscription() method
=====================================

The **`PushManager.getSubscription()`** method of the `PushManager` interface retrieves an existing push subscription.

It returns a `Promise` that resolves to a `PushSubscription` object containing details of an existing subscription. If no existing subscription exists, this resolves to a `null` value.

Syntax
------

```js
getSubscription()
```

### Parameters

None.

### Return value

A `Promise` that resolves to a `PushSubscription` object or `null`.

Examples
--------

This code snippet is taken from a push messaging and notification sample. (No live demo is available.)

```js
// We need the service worker registration to check for a subscription
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
  // Do we already have a push message subscription?
  serviceWorkerRegistration.pushManager
    .getSubscription()
    .then((subscription) => {
      // Enable any UI which subscribes / unsubscribes from
      // push messages.
      const pushButton = document.querySelector(".js-push-button");
      pushButton.disabled = false;

      if (!subscription) {
        // We aren't subscribed to push, so set UI
        // to allow the user to enable push
        return;
      }

      // Keep your server in sync with the latest subscriptionId
      sendSubscriptionToServer(subscription);

      showCurlCommand(subscription);

      // Set your UI to show they have subscribed for
      // push messages
      pushButton.textContent = "Disable Push Messages";
      isPushEnabled = true;
    })
    .catch((err) => {
      console.error(`Error during getSubscription(): ${err}`);
    });
});
```

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

| Specification |
| --- |
| Push API # dom-pushmanager-getsubscription |

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

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


PushManager: register() method - Web APIs

PushManager: register() method
==============================

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

 The **`register`** method is used to ask the system to request
 a new endpoint for notifications.

**Note:** This method has been superseded by `PushManager.subscribe()`.

Syntax
------

```js
register()
```

### Parameters

None.

### Return value

A `DOMRequest` object to handle the success or failure of the method call.

 If the method call is successful, the request's `result` will be a string,
 which is the endpoint URL.

**Note:** if you do not need the URL any more, please use
 `PushManager.unregister()` to clean up after yourself.

Examples
--------

```js
const req = navigator.push.register();

req.onsuccess = (e) => {
  const endpoint = req.result;
  console.log(`New endpoint: ${endpoint}`);
};

req.onerror = (e) => {
  console.error(`Error getting a new endpoint: ${e.error}`);
};
```

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

This feature is not part of any specification. It is no longer on track to become a standard.

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

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

See also
--------

* `PushManager`


PushManager: hasPermission() method - Web APIs

PushManager: hasPermission() method
===================================

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

The **`PushManager.hasPermission()`** method of the `PushManager` interface returns a `Promise` that resolves to the `PushPermissionStatus` of the requesting webapp, which will be one of `granted`, `denied`, or `default`.

**Note:** This feature has been superseded by the `PushManager.permissionState()` method.

Syntax
------

```js
hasPermission()
```

### Parameters

None.

### Return value

A `Promise` that resolves to the `PushPermissionStatus`.

Examples
--------

```js
// TBD
```

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

This feature is not part of any specification anymore. It is no longer on track to become a standard.

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

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


PushManager: unregister() method - Web APIs

PushManager: unregister() method
================================

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

 The **`unregister()`** method was used to ask the system to
 unregister and delete the specified endpoint.

**Note:** In the updated API, a subscription can be unregistered via the `PushSubscription.unsubscribe()` method.

Syntax
------

```js
unregister(pushEndpoint)
```

### Parameters

`pushEndpoint`

A pushEndpoint to be unregistered.

### Return value

A `DOMRequest` object to handle the success or failure of the method call.

 If the method call is successful, the request's `result` will be a
 PushRegistration object representing the endpoint that has been
 unregistered.

### PushRegistration

Those objects are anonymous JavaScript objects with the following properties:

`pushEndpoint`

A string representing the URL of the unregistered endpoint.

`version`

`Undefined` when `unregister.onsuccess` is called.

Examples
--------

```js
const req = navigator.push.unregister(pushEndpoint);

req.onsuccess = (e) => {
  const endpoint = req.result;
  console.log(`Unregistered endpoint: ${endpoint}`);
};

req.onerror = (e) => {
  console.error(`Error unregistering the endpoint: ${e.error}`);
};
```

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

This feature is not part of any specification anymore. It is no longer on track to become a standard.

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

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

See also
--------

* `PushManager`


PushManager: supportedContentEncodings static property - Web APIs

PushManager: supportedContentEncodings static property
======================================================

 The **`supportedContentEncodings`** read-only static property of the
 `PushManager` interface returns an array of supported content codings that
 can be used to encrypt the payload of a push message.

Value
-----

An array of strings.

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

| Specification |
| --- |
| Push API # dom-pushmanager-supportedcontentencodings |

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

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


PushManager: registrations() method - Web APIs

PushManager: registrations() method
===================================

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

 The **`registrations`** method is used to ask the system about
 existing push endpoint registrations.

**Note:** This method has been superseded by the `PushManager.getSubscription()` method.

Syntax
------

```js
registrations()
```

### Parameters

None.

### Return value

A `DOMRequest` object to handle the success or failure of the method call.

 If the method call is successful, the request's `result` will be an array of
 PushRegistration objects.

### PushRegistration

Those objects are anonymous JavaScript objects with the following properties:

`pushEndpoint`

A string representing the URL of the endpoint.

`version`

The current version that the push endpoint is at.

Examples
--------

```js
const req = navigator.push.registrations();

req.onsuccess = (e) => {
  if (req.result.length > 0) {
    req.result.forEach((result) => {
      console.log(
        `Existing registration ${result.pushEndpoint} ${result.version}`,
      );
    });
    // Reuse existing endpoints.
  } else {
    // Register for a new endpoint.
    const register = navigator.push.register();
    register.onsuccess = (e) => {
      console.log(`Registered new endpoint: ${register.result}`);
    };
  }
};
```

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

This feature is not part of any specification anymore. It is no longer on track to become a standard.

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

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

See also
--------

* `PushManager`


PushManager: subscribe() method - Web APIs

PushManager: subscribe() method
===============================

 The **`subscribe()`** method of the `PushManager`
 interface subscribes to a push service.

 It returns a `Promise` that resolves to a `PushSubscription`
 object containing details of a push subscription. A new push subscription is created if
 the current service worker does not have an existing subscription.

Syntax
------

```js
subscribe(options)
```

### Parameters

`options` Optional

 An object containing optional configuration parameters. It can have the following
 properties:

`userVisibleOnly`

 A boolean indicating that the returned push
 subscription will only be used for messages whose effect is made visible to the
 user.

`applicationServerKey`

 A Base64-encoded string or
 `ArrayBuffer` containing an ECDSA
 P-256 public key that the push server will use to authenticate your application
 server. If specified, all messages from your application server must use the VAPID authentication scheme, and
 include a JWT signed with the corresponding private key. This key ***IS
NOT*** the same ECDH key that you use to encrypt the data. For more
 information, see "Using VAPID with WebPush".

**Note:** This parameter is required in some browsers like
 Chrome and Edge. They will reject the Promise if `userVisibleOnly` is not set to `true`.

### Return value

A `Promise` that resolves to a `PushSubscription` object.

Examples
--------

```js
this.onpush = (event) => {
  console.log(event.data);
  // From here we can write the data to IndexedDB, send it to any open
  // windows, display a notification, etc.
};

navigator.serviceWorker.register("serviceworker.js");

// Use serviceWorker.ready to ensure that you can subscribe for push
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
  const options = {
    userVisibleOnly: true,
    applicationServerKey,
  };
  serviceWorkerRegistration.pushManager.subscribe(options).then(
    (pushSubscription) => {
      console.log(pushSubscription.endpoint);
      // The push subscription details needed by the application
      // server are now available, and can be sent to it using,
      // for example, the fetch() API.
    },
    (error) => {
      // During development it often helps to log errors to the
      // console. In a production environment it might make sense to
      // also report information about errors back to the
      // application server.
      console.error(error);
    },
  );
});
```

### Responding to user gestures

`subscribe()` calls should be done in response to a user gesture, such as
 clicking a button, for example:

```js
btn.addEventListener("click", () => {
  serviceWorkerRegistration.pushManager
    .subscribe(options)
    .then((pushSubscription) => {
      // handle subscription
    });
});
```

 This is not only best practice — you should not be spamming users with notifications
 they didn't agree to — but going forward browsers will explicitly disallow notifications
 not triggered in response to a user gesture. Firefox is already doing this from version
 72, for example.

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

| Specification |
| --- |
| Push API # dom-pushmanager-subscribe |

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

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


PushManager: permissionState() method - Web APIs

PushManager: permissionState() method
=====================================

 The **`permissionState()`** method of the
 `PushManager` interface returns a `Promise` that resolves to a
 string indicating the permission state of the push manager. Possible
 values are `'prompt'`, `'denied'`, or `'granted'`.

**Note:** As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is
 granted for notifications, push will also be enabled.

Syntax
------

```js
permissionState()
permissionState(options)
```

### Parameters

`options` Optional

 An object containing optional configuration parameters. It can have the following
 properties:

`userVisibleOnly`

 A boolean indicating that the returned push
 subscription will only be used for messages whose effect is made visible to the
 user.

`applicationServerKey`

 A public key your push server will use to
 send messages to client apps via a push server. This value is part of a signing
 key pair generated by your application server and usable with elliptic curve
 digital signature (ECDSA) over the P-256 curve.

### Return value

 A `Promise` that resolves to a string with a value of
 `'prompt'`, `'denied'`, or `'granted'`.

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

| Specification |
| --- |
| Push API # dom-pushmanager-permissionstate |

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

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