Sensor APIs - Web APIs

Sensor APIs
===========

The **Sensor APIs** are a set of interfaces built to a common design that expose device sensors in a consistent way to the web platform.

Sensor APIs concepts and usage
------------------------------

Although the Generic Sensor API specification defines a `Sensor` interface, as a web developer you will never use it. Instead you'll use one of its subclasses to retrieve specific kinds of sensor data. For example, the `Accelerometer` interface returns the acceleration of the device along all three axes at the time it is read.

Sensors may or may not correspond exactly to a physical device sensor. For example, the `Gyroscope` interface corresponds exactly to a physical device interface. Alternatively, the `AbsoluteOrientationSensor` interface provides information that is algorithmically aggregated from two or more device sensors. These sensor types are referred to as *low-level* and *high-level* respectively. The latter type of sensor is also called a fusion sensor (alternatively, virtual or synthetic sensors).

### Feature detection

Sensor interfaces are only proxies for the underlying device sensors. Consequently, feature detection is more complicated for sensors than it is for other APIs. The presence of a sensor API does not tell you whether that API is connected to a real hardware sensor, whether that sensor works, if it's still connected, or even whether the user has granted access to it. Making all this information consistently available is costly to performance and battery life.

Therefore, feature detection for sensor APIs must include both detection of the APIs themselves and defensive programming strategies (see below).

The examples below show three methods for detecting sensor APIs. Additionally you can put object instantiation inside a `try...catch` block. Notice that detection through the `Navigator` interface is not one of the available options.

```js
if (typeof Gyroscope === "function") {
  // run in circles…
}

if ("ProximitySensor" in window) {
  // watch out!
}

if (window.AmbientLightSensor) {
  // go dark…
}
```

### Defensive programming

As stated in Feature Detection, checking for a particular sensor API is insufficient for feature detection. The existence of an actual sensor must be confirmed as well. This is where defensive programming is needed. Defensive programming requires three strategies.

* Checking for thrown errors when instantiating a sensor object.
* Listening for errors thrown during its use.
* Handling the errors gracefully so that the user experience is enhanced rather than degraded.

The code example below illustrates these principles. The `try...catch` block catches errors thrown during sensor instantiation. It listens for `error` events to catch errors thrown during use. The only time anything is shown to the user is when permissions need to be requested and when the sensor type isn't supported by the device.

In addition, this feature may be blocked by a Permissions Policy set on your server.

```js
let accelerometer = null;
try {
  accelerometer = new Accelerometer({ referenceFrame: "device" });
  accelerometer.addEventListener("error", (event) => {
    // Handle runtime errors.
    if (event.error.name === "NotAllowedError") {
      // Branch to code for requesting permission.
    } else if (event.error.name === "NotReadableError") {
      console.log("Cannot connect to the sensor.");
    }
  });
  accelerometer.addEventListener("reading", () => reloadOnShake(accelerometer));
  accelerometer.start();
} catch (error) {
  // Handle construction errors.
  if (error.name === "SecurityError") {
    // See the note above about permissions policy.
    console.log("Sensor construction was blocked by a permissions policy.");
  } else if (error.name === "ReferenceError") {
    console.log("Sensor is not supported by the User Agent.");
  } else {
    throw error;
  }
}
```

### Permissions and Permissions Policy

Sensor readings may not be taken unless the user grants permission to a specific sensor type using the Permissions API and/or if access is not blocked by the server `Permissions-Policy`.

The example below shows how to request user-permission before attempting to use the sensor.

```js
navigator.permissions.query({ name: "accelerometer" }).then((result) => {
  if (result.state === "denied") {
    console.log("Permission to use accelerometer sensor is denied.");
    return;
  }
  // Use the sensor.
});
```

An alternative approach is to attempt to use the sensor and listen for the `SecurityError`.

```js
const sensor = new AbsoluteOrientationSensor();
sensor.start();
sensor.addEventListener("error", (error) => {
  if (event.error.name === "SecurityError")
    console.log("No permissions to use AbsoluteOrientationSensor.");
});
```

The following table describes for each sensor type, the name required for the Permissions API, the `<iframe>` element's `allow` attribute and the `Permissions-Policy` directive.

| Sensor | Permission Policy Name |
| --- | --- |
| `AbsoluteOrientationSensor` | `'accelerometer'`, `'gyroscope'`, and `'magnetometer'` |
| `Accelerometer` | `'accelerometer'` |
| `AmbientLightSensor` | `'ambient-light-sensor'` |
| `GravitySensor` | `'accelerometer'` |
| `Gyroscope` | `'gyroscope'` |
| `LinearAccelerationSensor` | `'accelerometer'` |
| `Magnetometer` | `'magnetometer'` |
| `RelativeOrientationSensor` | `'accelerometer'`, and `'gyroscope'` |

### Readings

Sensor readings are received through the `reading` event callback which is inherited by all sensor types. Reading frequency is decided by you, accomplished with an option passed to a sensor's constructor. The option is a number that specifies the number of readings per second. A whole number or decimal may be used, the latter for frequencies less than a second. The actual reading frequency depends on device hardware and consequently may be less than requested.

The following example illustrates this using the `Magnetometer` sensor.

```js
let magSensor = new Magnetometer({ frequency: 60 });

magSensor.addEventListener("reading", (e) => {
  console.log(`Magnetic field along the X-axis ${magSensor.x}`);
  console.log(`Magnetic field along the Y-axis ${magSensor.y}`);
  console.log(`Magnetic field along the Z-axis ${magSensor.z}`);
});
magSensor.addEventListener("error", (event) => {
  console.log(event.error.name, event.error.message);
});
magSensor.start();
```

Interfaces
----------

`AbsoluteOrientationSensor` Secure context

Describes the device's physical orientation in relation to the Earth's reference coordinate system.

`Accelerometer` Secure context

Provides the acceleration applied to the device along all three axes.

`AmbientLightSensor` Secure context

Returns the current light level or illuminance of the ambient light around the hosting device.

`GravitySensor` Secure context

Provides the gravity applied to the device along all three axes.

`Gyroscope` Secure context

Provides the angular velocity of the device along all three axes.

`LinearAccelerationSensor` Secure context

Provides the acceleration applied to the device along all three axes, but without the contribution of gravity.

`Magnetometer` Secure context

Provides information about the magnetic field as detected by the device's primary magnetometer sensor.

`OrientationSensor` Secure context

The base class for the `AbsoluteOrientationSensor`. This interface cannot be used directly, instead it provides properties and methods accessed by interfaces that inherit from it.

`RelativeOrientationSensor` Secure context

Describes the device's physical orientation without regard to the Earth's reference coordinate system.

`Sensor` Secure context

The base class for all the other sensor interfaces. This interface cannot be used directly. Instead, it provides properties, event handlers, and methods accessed by interfaces that inherit from it.

`SensorErrorEvent` Secure context

Provides information about errors thrown by a `Sensor` or related interface.

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

| Specification |
| --- |
| Generic Sensor API # the-sensor-interface |

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

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


ReadableByteStreamController - Web APIs

ReadableByteStreamController
============================

 The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream.
 It allows control of the state and internal queue of a `ReadableStream` with an underlying byte source, and enables efficient zero-copy transfer of data from the underlying source to a consumer when the stream's internal queue is empty.

 An instance of this controller type is created if an `underlyingSource` object with the property `type="bytes"` is passed as an argument to the `ReadableStream()` constructor.
 The `underlyingSource` object may also define `start()` and `pull()` callback functions.
 These are called with the controller as a parameter, in order to set up the underlying source, and request data when needed.

 The underlying source uses the controller to supply data to the stream via its `byobRequest` property or `enqueue()` method.
 `byobRequest` is a `ReadableStreamBYOBRequest` object that represents a pending request from a consumer to make a zero-copy transfer of data direct to a consumer.
 `byobRequest` must be used to copy data if it exists (do not use `enqueue()` in this case)!
 If the underlying source needs to pass data to the stream and `byobRequest` is `null` then the source can call `enqueue()` to add the data to the stream's internal queues.

 Note that the `byobRequest` is only created in "BYOB mode" when there is a request from a reader and the stream's internal queue is empty.
 "BYOB mode" is enabled when using a `ReadableStreamBYOBReader` (typically constructed by calling `ReadableStream.getReader()` with the argument `{ mode: 'byob' }`).
 It is also enabled when using a default reader and `autoAllocateChunkSize` is specified in the `ReadableController()` constructor.

 An underlying byte source can also use the controller to `close()` the stream when all the data has been sent and report errors from the underlying source using `error()`.
 The controller's `desiredSize` property is used to apply "backpressure", informing the underlying source of the size of the internal queue (small values indicate that the queue is filling up, hinting to the underlying source that it is be desirable to pause or throttle the inflow).

Note that even though the controller is primarily used by the underlying byte source, there is no reason it cannot be stored used by other parts of the system to signal the stream.

Constructor
-----------

None. `ReadableByteStreamController` instances are automatically created if an `underlyingSource` with the property `type="bytes"` is passed to the `ReadableStream()` constructor.

Instance properties
-------------------

`ReadableByteStreamController.byobRequest` Read only

Returns the current BYOB pull request, or `null` if there no outstanding request.

`ReadableByteStreamController.desiredSize` Read only

Returns the desired size required to fill the stream's internal queue.

Instance methods
----------------

`ReadableByteStreamController.close()`

Closes the associated stream.

`ReadableByteStreamController.enqueue()`

Enqueues a given chunk in the associated stream.

`ReadableByteStreamController.error()`

Causes any future interactions with the associated stream to error.

Examples
--------

The controller is used by an underlying source to transfer or enqueue data, to signal that the stream has no more data (has closed) or has errored. It is also used to signal the underlying source from "upstream" of the desired data rate, using `desiredSize`.

The example in Using readable byte streams, in particular Creating a readable socket push byte stream, show most of these cases.

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

| Specification |
| --- |
| Streams Standard # rbs-controller-class |

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

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

See also
--------

* Streams API concepts
* Using readable byte streams
* `ReadableStream`
* WHATWG Stream Visualizer, for a basic visualization of readable, writable, and transform streams.
* Web-streams-polyfill or sd-streams - polyfills


CSSSkew - Web APIs

CSSSkew
=======

The **`CSSSkew`** interface of the CSS\_Object\_Model#css\_typed\_object\_model is part of the `CSSTransformValue` interface. It represents the `skew()` value of the individual `transform` property in CSS.

CSSTransformComponent

CSSSkewConstructor
-----------

`CSSSkew()`

Creates a new `CSSSkew` object.

Instance properties
-------------------

`ax`

Returns or sets the x-axis value.

`ay`

Returns or sets the y-axis value.

Examples
--------

To Do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # cssskew |

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

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


XRReferenceSpaceEvent - Web APIs

XRReferenceSpaceEvent
=====================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The WebXR Device API interface **`XRReferenceSpaceEvent`** represents an event sent to an `XRReferenceSpace`. Currently, the only event that uses this type is the `reset` event.

Event

XRReferenceSpaceEventConstructor
-----------

`XRReferenceSpaceEvent()`

Returns a new `XRReferenceSpaceEvent` with the specified type and configuration.

Instance properties
-------------------

*In addition to inheriting the properties available on the parent interface, `Event`, `XRReferenceSpaceEvent` objects include the following properties:*

`referenceSpace` Read only

An `XRReferenceSpace` indicating the reference space that generated the event.

`transform` Read only

An `XRRigidTransform` object indicating the position and orientation of the specified `referenceSpace`'s native origin after the event, defined relative to the coordinate system before the event.

Instance methods
----------------

*While `XRReferenceSpaceEvent` does not define any methods, it inherits the methods of its parent interface, `Event`.*

Event types
-----------

`reset`

The `reset` event is sent to a reference space when its native origin is changed due to a discontinuity, recalibration, or device reset. This is an opportunity for your app to update any stored transforms, position/orientation information, or the like—or to dump any cached values based on the reference's space's origin so you can recompute them as needed.

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

| Specification |
| --- |
| WebXR Device API # xrreferencespaceevent-interface |

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

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


FocusEvent - Web APIs

FocusEvent
==========

The **`FocusEvent`** interface represents focus-related events, including `focus`, `blur`, `focusin`, and `focusout`.

Event

UIEvent

FocusEventConstructor
-----------

`FocusEvent()`

Creates a `FocusEvent` event with the given parameters.

Instance properties
-------------------

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

`FocusEvent.relatedTarget`

An `EventTarget` representing a secondary target for this event. In some cases (such as when tabbing in or out a page), this property may be set to `null` for security reasons.

Instance methods
----------------

*This interface has no specific methods. It inherits methods from its parent `UIEvent`, and indirectly from `Event`.*

Order of events
---------------

When focus is shifted from element A to element B, focus events are dispatched in the following order:

1. `blur`: sent after element A loses focus.
2. `focusout`: sent after the `blur` event.
3. `focus`: sent after element B receives focus.
4. `focusin`: sent after the `focus` event.
Specifications
--------------

| Specification |
| --- |
| UI Events # interface-focusevent |

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

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

See also
--------

* The `Event` base interface


SVGGElement - Web APIs

SVGGElement
===========

The **`SVGGElement`** interface corresponds to the `<g>` element.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGGElementInstance properties
-------------------

*This interface doesn't implement any specific properties, but inherits properties from its parent interface, `SVGGraphicsElement`.*

Instance methods
----------------

*This interface doesn't implement any specific methods, but inherits methods from its parent interface, `SVGGraphicsElement`.*

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # InterfaceSVGGElement |

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

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


MediaSource - Web APIs

MediaSource
===========

The **`MediaSource`** interface of the Media Source Extensions API represents a source of media data for an `HTMLMediaElement` object. A `MediaSource` object can be attached to a `HTMLMediaElement` to be played in the user agent.

EventTarget

MediaSourceConstructor
-----------

`MediaSource()`

Constructs and returns a new `MediaSource` object with no associated source buffers.

Instance properties
-------------------

`MediaSource.activeSourceBuffers` Read only

Returns a `SourceBufferList` object containing a subset of the `SourceBuffer` objects contained within `MediaSource.sourceBuffers` — the list of objects providing the selected video track, enabled audio tracks, and shown/hidden text tracks.

`MediaSource.duration`

Gets and sets the duration of the current media being presented.

`MediaSource.handle` Read only
Experimental

Inside a dedicated worker, returns a `MediaSourceHandle` object, a proxy for the `MediaSource` that can be transferred from the worker back to the main thread and attached to a media element via its `HTMLMediaElement.srcObject` property.

`MediaSource.readyState` Read only

Returns an enum representing the state of the current `MediaSource`, whether it is not currently attached to a media element (`closed`), attached and ready to receive `SourceBuffer` objects (`open`), or attached but the stream has been ended via `MediaSource.endOfStream()` (`ended`.)

`MediaSource.sourceBuffers` Read only

Returns a `SourceBufferList` object containing the list of `SourceBuffer` objects associated with this `MediaSource`.

Static properties
-----------------

`MediaSource.canConstructInDedicatedWorker` Read only
Experimental

A boolean; returns `true` if `MediaSource` worker support is implemented, providing a low-latency feature detection mechanism.

Instance methods
----------------

*Inherits methods from its parent interface, `EventTarget`.*

`MediaSource.addSourceBuffer()`

Creates a new `SourceBuffer` of the given MIME type and adds it to the `MediaSource.sourceBuffers` list.

`MediaSource.clearLiveSeekableRange()`

Clears a seekable range previously set with a call to `setLiveSeekableRange()`.

`MediaSource.endOfStream()`

Signals the end of the stream.

`MediaSource.removeSourceBuffer()`

Removes the given `SourceBuffer` from the `MediaSource.sourceBuffers` list.

`MediaSource.setLiveSeekableRange()`

Sets the range that the user can seek to in the media element.

Static methods
--------------

`MediaSource.isTypeSupported()`

Returns a boolean value indicating if the given MIME type is supported by the current user agent — this is, if it can successfully create `SourceBuffer` objects for that MIME type.

Events
------

`sourceclose`

Fired when the `MediaSource` instance is not attached to a media element anymore.

`sourceended`

Fired when the `MediaSource` instance is still attached to a media element, but `endOfStream()` has been called.

`sourceopen`

Fired when the `MediaSource` instance has been opened by a media element and is ready for data to be appended to the `SourceBuffer` objects in `sourceBuffers`.

Examples
--------

### Complete basic example

The following simple example loads a video with `XMLHttpRequest`, playing it as soon as it can. This example was written by Nick Desaulniers and can be viewed live here (you can also download the source for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

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

const assetURL = "frag\_bunny.mp4";
// Need to be specific for Blink regarding codecs
// ./mp4info frag\_bunny.mp4 | grep Codec
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
let mediaSource;

if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) {
  mediaSource = getMediaSource();
  console.log(mediaSource.readyState); // closed
  video.src = URL.createObjectURL(mediaSource);
  mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
  console.error("Unsupported MIME type or codec: ", mimeCodec);
}

function sourceOpen() {
  console.log(this.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}

function fetchAB(url, cb) {
  console.log(url);
  const xhr = new XMLHttpRequest();
  xhr.open("get", url);
  xhr.responseType = "arraybuffer";
  xhr.onload = () => {
    cb(xhr.response);
  };
  xhr.send();
}
```

### Constructing a `MediaSource` in a dedicated worker and passing it to the main thread

The `handle` property can be accessed inside a dedicated worker and the resulting `MediaSourceHandle` object is then transferred over to the thread that created the worker (in this case the main thread) via a `postMessage()` call:

```js
// Inside dedicated worker
let mediaSource = new MediaSource();
let handle = mediaSource.handle;
// Transfer the handle to the context that created the worker
postMessage({ arg: handle }, [handle]);

mediaSource.addEventListener("sourceopen", () => {
  // Await sourceopen on MediaSource before creating SourceBuffers
  // and populating them with fetched media — MediaSource won't
  // accept creation of SourceBuffers until it is attached to the
  // HTMLMediaElement and its readyState is "open"
});
```

Over in the main thread, we receive the handle via a `message` event handler, attach it to a `<video>` via its `HTMLMediaElement.srcObject` property, and `play` the video:

```js
worker.addEventListener("message", (msg) => {
  let mediaSourceHandle = msg.data.arg;
  video.srcObject = mediaSourceHandle;
  video.play();
});
```

**Note:** `MediaSourceHandle`s cannot be successfully transferred into or via a shared worker or service worker.

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

| Specification |
| --- |
| Media Source Extensions™ # mediasource |

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


scheduler global property - Web APIs

scheduler global 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 global read-only **`scheduler`** property is the entry point for using the Prioritized Task Scheduling API.

 It is implemented by both `Window` and `WorkerGlobalScope`.
 The existence of the property indicates that the API is supported in the current context, and can be accessed using `this.scheduler`.

The object has a single instance method `Scheduler.postTask()` that is used to post prioritized tasks for scheduling.

Value
-----

A `Scheduler`.

Examples
--------

 The code below shows a very basic use of the property and its associated interface.
 It demonstrates how to check that the property exists and then posts a task that returns a promise.

```js
// Check if the prioritized task API is supported
if ("scheduler" in this) {
  // Callback function - "the task"
  const myTask = () => "Task 1: user-visible";

  // Post task with default priority: 'user-visible' (no other options)
  // When the task resolves, Promise.then() logs the result.
  scheduler
    .postTask(myTask)
    // Handle resolved value
    .then((taskResult) => console.log(`${taskResult}`))
    // Handle error or abort
    .catch((error) => console.log(`Error: ${error}`));
} else {
  console.log("Feature: NOT Supported");
}
```

For comprehensive example code showing to use the API see Prioritized Task Scheduling API > Examples.

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

| Specification |
| --- |
| Prioritized Task Scheduling # dom-windoworworkerglobalscope-scheduler |

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

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

See also
--------

* Prioritized Task Scheduling API
* `Scheduler.postTask()`
* `TaskController`


GPUValidationError - Web APIs

GPUValidationError
==================

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

The **`GPUValidationError`** interface of the WebGPU API describes an application error indicating that an operation did not pass the WebGPU API's validation constraints.

It represents one of the types of errors surfaced by `GPUDevice.popErrorScope` and the `uncapturederror` event.

Validation errors occur whenever invalid inputs are given to a WebGPU call. These are consistent, predictable, and should not occur provided your app is well-formed. They will occur in the same way on every device your code runs on, so once you've fixed any errors that show up during development you probably don't need to observe them directly most of the time. An exception to that rule is if you're consuming user-supplied assets, shaders, etc., in which case watching for validation errors while loading could be helpful.

**Note:** We have attempted to provide useful information to help you understand why validation errors are occurring in your WebGPU code in "Validation" sections where appropriate, which list criteria to meet to avoid validation errors. See for example the `GPUDevice.createBindGroup()` Validation section.

GPUError

GPUValidationErrorConstructor
-----------

`GPUValidationError()`
Experimental

Creates a new `GPUValidationError` object instance.

Instance properties
-------------------

The `message` property is inherited from its parent, `GPUError`:

`message`
Experimental
 Read only

A string providing a human-readable message that explains why the error occurred.

Examples
--------

The following example uses an error scope to capture a suspected validation error, logging it to the console.

```js
device.pushErrorScope("validation");

let sampler = device.createSampler({
  maxAnisotropy: 0, // Invalid, maxAnisotropy must be at least 1.
});

device.popErrorScope().then((error) => {
  if (error) {
    // error is a GPUValidationError object instance
    sampler = null;
    console.error(`An error occurred while creating sampler: ${error.message}`);
  }
});
```

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

| Specification |
| --- |
| WebGPU # gpuvalidationerror |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


SVGSVGElement - Web APIs

SVGSVGElement
=============

The **`SVGSVGElement`** interface provides access to the properties of `<svg>` elements, as well as methods to manipulate them. This interface contains also various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGSVGElementInstance properties
-------------------

*This interface also inherits properties from its parent, `SVGGraphicsElement`.*

`SVGSVGElement.x` Read only

An `SVGAnimatedLength` corresponding to the `x` attribute of the given `<svg>` element.

`SVGSVGElement.y` Read only

An `SVGAnimatedLength` corresponding to the `y` attribute of the given `<svg>` element.

`SVGSVGElement.width` Read only

An `SVGAnimatedLength` corresponding to the `width` attribute of the given `<svg>` element.

`SVGSVGElement.height` Read only

An `SVGAnimatedLength` corresponding to the `height` attribute of the given `<svg>` element.

`SVGSVGElement.pixelUnitToMillimeterX`
Deprecated

A float representing the size of the pixel unit (as defined by CSS2) along the x-axis of the viewport, which represents a unit somewhere in the range of 70dpi to 120dpi, and, on systems that support this, might actually match the characteristics of the target medium. On systems where it is impossible to know the size of a pixel, a suitable default pixel size is provided.

`SVGSVGElement.pixelUnitToMillimeterY`
Deprecated

A float representing the size of a pixel unit along the y-axis of the viewport.

`SVGSVGElement.screenPixelToMillimeterX`
Deprecated

User interface (UI) events in DOM Level 2 indicate the screen positions at which the given UI event occurred. When the browser actually knows the physical size of a "screen unit", this float attribute will express that information; otherwise, user agents will provide a suitable default value (such as `.28mm`).

`SVGSVGElement.screenPixelToMillimeterY`
Deprecated

Corresponding size of a screen pixel along the y-axis of the viewport.

`SVGSVGElement.useCurrentView`
Deprecated

Non-standard

The initial view (i.e., before magnification and panning) of the current innermost SVG document fragment can be either the "standard" view, i.e., based on attributes on the `<svg>` element such as `viewBox`) or on a "custom" view (i.e., a hyperlink into a particular `<view>` or other element). If the initial view is the "standard" view, then this attribute is `false`. If the initial view is a "custom" view, then this attribute is `true`.

`SVGSVGElement.currentView`
Deprecated

Non-standard

An `SVGViewSpec` defining the initial view (i.e., before magnification and panning) of the current innermost SVG document fragment. The meaning depends on the situation: If the initial view was a "standard" view, then:

* the values for `viewBox`, `preserveAspectRatio` and `zoomAndPan` within `currentView` will match the values for the corresponding DOM attributes that are on `SVGSVGElement` directly
* the value for `transform` within `currentView` will be `null`

If the initial view was a link into a `<view>` element, then:

* the values for `viewBox`, `preserveAspectRatio` and `zoomAndPan` within `currentView` will correspond to the corresponding attributes for the given `<view>` element
* the value for `transform` within `currentView` will be `null`

If the initial view was a link into another element (i.e., other than a `<view>`), then:

* the values for `viewBox`, `preserveAspectRatio` and `zoomAndPan` within `currentView` will match the values for the corresponding DOM attributes that are on `SVGSVGElement` directly for the closest ancestor `<svg>` element
* the values for `transform` within `currentView` will be `null`

If the initial view was a link into the SVG document fragment using an SVG view specification fragment identifier (i.e., `#svgView(…)`), then:

* the values for `viewBox`, `preserveAspectRatio`, `zoomAndPan`, `transform` within `currentView` will correspond to the values from the SVG view specification fragment identifier

`SVGSVGElement.currentScale`

On an outermost `<svg>` element, this float attribute indicates the current scale factor relative to the initial view to take into account user magnification and panning operations. DOM attributes `currentScale` and `currentTranslate` are equivalent to the 2×3 matrix `[a b c d e f] = [currentScale 0 0 currentScale currentTranslate.x currentTranslate.y]`. If "magnification" is enabled (i.e., `zoomAndPan="magnify"`), then the effect is as if an extra transformation were placed at the outermost level on the SVG document fragment (i.e., outside the outermost `<svg>` element).

`SVGSVGElement.currentTranslate` Read only

An `SVGPoint` representing the translation factor that takes into account user "magnification" corresponding to an outermost `<svg>` element. The behavior is undefined for `<svg>` elements that are not at the outermost level.

Instance methods
----------------

*This interface also inherits methods from its parent, `SVGGraphicsElement`.*

`SVGSVGElement.suspendRedraw()`
Deprecated

Takes a time-out value which indicates that redraw shall not occur until:

the corresponding `unsuspendRedraw()` call has been made, an `unsuspendRedrawAll()` call has been made, or its timer has timed out.

In environments that do not support interactivity (e.g., print media), then redraw shall not be suspended. Calls to `suspendRedraw()` and `unsuspendRedraw()` should, but need not be, made in balanced pairs.

To suspend redraw actions as a collection of SVG DOM changes occur, precede the changes to the SVG DOM with a method call similar to:

```js
const suspendHandleID = suspendRedraw(maxWaitMilliseconds);
```

and follow the changes with a method call similar to:

```js
unsuspendRedraw(suspendHandleID);
```

Note that multiple `suspendRedraw()` calls can be used at once, and that each such method call is treated independently of the other `suspendRedraw()` method calls.

`SVGSVGElement.unsuspendRedraw()`
Deprecated

Cancels a specified `suspendRedraw()` by providing a unique suspend handle ID that was returned by a previous `suspendRedraw()` call.

`SVGSVGElement.unsuspendRedrawAll()`
Deprecated

Cancels all currently active `suspendRedraw()` method calls. This method is most useful at the very end of a set of SVG DOM calls to ensure that all pending `suspendRedraw()` method calls have been cancelled.

`SVGSVGElement.forceRedraw()`
Deprecated

In rendering environments supporting interactivity, forces the user agent to immediately redraw all regions of the viewport that require updating.

`SVGSVGElement.pauseAnimations()`

Suspends (i.e., pauses) all currently running animations that are defined within the SVG document fragment corresponding to this `<svg>` element, causing the animation clock corresponding to this document fragment to stand still until it is unpaused.

`SVGSVGElement.unpauseAnimations()`

Resumes (i.e., unpauses) currently running animations that are defined within the SVG document fragment, causing the animation clock to continue from the time at which it was suspended.

`SVGSVGElement.animationsPaused()`

Returns `true` if this SVG document fragment is in a paused state.

`SVGSVGElement.getCurrentTime()`

Returns the current time in seconds relative to the start time for the current SVG document fragment. If `getCurrentTime()` is called before the document timeline has begun (for example, by script running in a `<script>` element before the document's `SVGLoad` event is dispatched), then `0` is returned.

`SVGSVGElement.setCurrentTime()`

Adjusts the clock for this SVG document fragment, establishing a new current time. If `setCurrentTime()` is called before the document timeline has begun (for example, by script running in a `<script>` element before the document's `SVGLoad` event is dispatched), then the value of seconds in the last invocation of the method gives the time that the document will seek to once the document timeline has begun.

`SVGSVGElement.getIntersectionList()`

Returns a `NodeList` of graphics elements whose rendered content intersects the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in `pointer-events` processing.

`SVGSVGElement.getEnclosureList()`

Returns a `NodeList` of graphics elements whose rendered content is entirely contained within the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in `pointer-events` processing.

`SVGSVGElement.checkIntersection()`

Returns `true` if the rendered content of the given element intersects the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in `pointer-events` processing.

`SVGSVGElement.checkEnclosure()`

Returns `true` if the rendered content of the given element is entirely contained within the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in `pointer-events` processing.

`SVGSVGElement.deselectAll()`

Unselects any selected objects, including any selections of text strings and type-in bars.

`SVGSVGElement.createSVGNumber()`

Creates an `SVGNumber` object outside of any document trees. The object is initialized to `0`.

`SVGSVGElement.createSVGLength()`

Creates an `SVGLength` object outside of any document trees. The object is initialized to `0` user units.

`SVGSVGElement.createSVGAngle()`

Creates an `SVGAngle` object outside of any document trees. The object is initialized to a value of `0` degrees (unitless).

`SVGSVGElement.createSVGPoint()`

Creates an `SVGPoint` object outside of any document trees. The object is initialized to the point `(0,0)` in the user coordinate system.

`SVGSVGElement.createSVGMatrix()`

Creates an `SVGMatrix` object outside of any document trees. The object is initialized to the identity matrix.

`SVGSVGElement.createSVGRect()`

Creates an `SVGRect` object outside of any document trees. The object is initialized such that all values are set to `0` user units.

`SVGSVGElement.createSVGTransform()`

Creates an `SVGTransform` object outside of any document trees. The object is initialized to an identity matrix transform (`SVG_TRANSFORM_MATRIX`).

`SVGSVGElement.createSVGTransformFromMatrix()`

Creates an `SVGTransform` object outside of any document trees. The object is initialized to the given matrix transform (i.e., `SVG_TRANSFORM_MATRIX`). The values from the parameter matrix are copied, the matrix parameter is not adopted as `SVGTransform::matrix`.

`SVGSVGElement.getElementById()`

Searches this SVG document fragment (i.e., the search is restricted to a subset of the document tree) for an Element whose `id` is given by `elementId`. If an Element is found, that Element is returned. If no such element exists, returns `null`. Behavior is not defined if more than one element has this id.

Event handlers
--------------

The following `Window` `onXYZ` event handler properties are also available as aliases targeting the `window` object. However, it is advised to listen to them on the `window` object directly rather than on `SVGSVGElement`.

**Note:** Using `addEventListener()` on `SVGSVGElement` will not work for the `onXYZ` event handlers listed below. Listen to the events on the `window` object instead.

`SVGSVGElement.onafterprint`

Fired after the associated document has started printing or the print preview has been closed.

`SVGSVGElement.onbeforeprint`

Fired when the associated document is about to be printed or previewed for printing.

`SVGSVGElement.onbeforeunload`

Fired when the window, the document and its resources are about to be unloaded.

`SVGSVGElement.ongamepadconnected`

Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.

`SVGSVGElement.ongamepaddisconnected`

Fired when the browser detects that a gamepad has been disconnected.

`SVGSVGElement.onhashchange`

Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol).

`SVGSVGElement.onlanguagechange`

Fired when the user's preferred language changes.

`SVGSVGElement.onmessage`

Fired when the window receives a message, for example from a call to `Window.postMessage()` from another browsing context.

`SVGSVGElement.onmessageerror`

Fired when the window receives a message that can't be deserialized.

`SVGSVGElement.onoffline`

Fired when the browser has lost access to the network and the value of `Navigator.onLine` switches to `false`.

`SVGSVGElement.ononline`

Fired when the browser has gained access to the network and the value of `Navigator.onLine` switches to `true`.

`SVGSVGElement.onpagehide`

Fired when the browser hides the current page in the process of presenting a different page from the session's history.

`SVGSVGElement.onpageshow`

Fired when the browser displays the window's document due to navigation.

`SVGSVGElement.onpopstate`

Fired when the active history entry changes while the user navigates the session history.

`SVGSVGElement.onrejectionhandled`

Fired whenever a JavaScript `Promise` is rejected and the rejection has been handled.

`SVGSVGElement.onstorage`

Fired when a storage area (`localStorage`) has been modified in the context of another document.

`SVGSVGElement.onunhandledrejection`

Fired whenever a `Promise` is rejected but the rejection was not handled.

`SVGSVGElement.onunload`

Fired when the document is being unloaded.

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # InterfaceSVGSVGElement |

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

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

See also
--------

* `<circle>`


HTMLSelectElement - Web APIs

HTMLSelectElement
=================

The **`HTMLSelectElement`** interface represents a `<select>` HTML Element. These elements also share all of the properties and methods of other HTML elements via the `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLSelectElementInstance properties
-------------------

*This interface inherits the properties of `HTMLElement`, and of `Element` and `Node`.*

`HTMLSelectElement.disabled`

A boolean value reflecting the `disabled` HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks.

`HTMLSelectElement.form` Read only

An `HTMLFormElement` referencing the form that this element is associated with. If the element is not associated with of a `<form>` element, then it returns `null`.

`HTMLSelectElement.labels` Read only

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

`HTMLSelectElement.length`

An `unsigned long` The number of `<option>` elements in this `select` element.

`HTMLSelectElement.multiple`

A boolean value reflecting the `multiple` HTML attribute, which indicates whether multiple items can be selected.

`HTMLSelectElement.name`

A string reflecting the `name` HTML attribute, containing the name of this control used by servers and DOM search functions.

`HTMLSelectElement.options` Read only

An `HTMLOptionsCollection` representing the set of `<option>` (`HTMLOptionElement`) elements contained by this element.

`HTMLSelectElement.required`

A boolean value reflecting the `required` HTML attribute, which indicates whether the user is required to select a value before submitting the form.

`HTMLSelectElement.selectedIndex`

A `long` reflecting the index of the first selected `<option>` element. The value `-1` indicates no element is selected.

`HTMLSelectElement.selectedOptions` Read only

An `HTMLCollection` representing the set of `<option>` elements that are selected.

`HTMLSelectElement.size`

A `long` reflecting the `size` HTML attribute, which contains the number of visible items in the control. The default is 1, unless `multiple` is `true`, in which case it is 4.

`HTMLSelectElement.type` Read only

A string representing the form control's type. When `multiple` is `true`, it returns `"select-multiple"`; otherwise, it returns `"select-one"`.

`HTMLSelectElement.validationMessage` Read only

A string representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (`willValidate` is false), or it satisfies its constraints.

`HTMLSelectElement.validity` Read only

A `ValidityState` reflecting the validity state that this control is in.

`HTMLSelectElement.value`

A string reflecting the value of the form control. Returns the `value` property of the first selected option element if there is one, otherwise the empty string.

`HTMLSelectElement.willValidate` Read only

A boolean value that indicates whether the button is a candidate for constraint validation. It is `false` if any conditions bar it from constraint validation.

Instance methods
----------------

*This interface inherits the methods of `HTMLElement`, and of `Element` and `Node`.*

`HTMLSelectElement.add()`

Adds an element to the collection of `option` elements for this `select` element.

`HTMLSelectElement.checkValidity()`

Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable `invalid` event at the element (and returns `false`).

`HTMLSelectElement.item()`

Gets an item from the options collection for this `<select>` element. You can also access an item by specifying the index in square brackets or parentheses, without calling this method explicitly.

`HTMLSelectElement.namedItem()`

Gets the item in the options collection with the specified name. The name string can match either the `id` or the `name` attribute of an option node. You can also access an item by specifying the name in square brackets or parentheses, without calling this method explicitly.

`HTMLSelectElement.remove()`

Removes the element at the specified index from the options collection for this `select` element.

`HTMLSelectElement.reportValidity()`

This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable `invalid` event at the element, and returns `false`; if there are no problems, it returns `true`.

`HTMLSelectElement.setCustomValidity()`

Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does *not* have a custom validity error.

`showPicker()`

Shows the option picker.

Events
------

*This interface inherits the events of `HTMLElement`, and of `Element` and `Node`.*

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface:

`change` event

Fires when the user selects an option.

`input` event

Fires when the `value` of an `<input>`, `<select>`, or `<textarea>` element has been changed.

Example
-------

### Get information about the selected option

```js
/\* assuming we have the following HTML
<select id='s'>
 <option>First</option>
 <option selected>Second</option>
 <option>Third</option>
</select>
\*/

const select = document.getElementById("s");

// return the index of the selected option
console.log(select.selectedIndex); // 1

// return the value of the selected option
console.log(select.options[select.selectedIndex].value); // Second
```

A better way to track changes to the user's selection is to watch for the `change` event to occur on the `<select>`. This will tell you when the value changes, and you can then update anything you need to. See the example provided in the documentation for the `change` event for details.

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

| Specification |
| --- |
| HTML Standard # htmlselectelement |

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

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

See also
--------

* The `<select>` HTML element, which implements this interface.


PresentationConnectionCloseEvent - Web APIs

PresentationConnectionCloseEvent
================================

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

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`PresentationConnectionCloseEvent`** interface of the Presentation API is fired on a `PresentationConnection` when it is closed.

Event

PresentationConnectionCloseEventConstructor
-----------

`PresentationConnectionCloseEvent()`
Experimental

Creates a new PresentationConnectionCloseEvent.

Instance properties
-------------------

`PresentationConnectionCloseEvent.message` Read only
Experimental

A human-readable message that provides more information about why the connection was closed.

`PresentationConnectionCloseEvent.reason` Read only
Experimental

Indicates why the connection was closed. This property takes one of the following values: `error`, `closed`, or `wentaway`.

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

| Specification |
| --- |
| Presentation API # interface-presentationconnectioncloseevent |

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

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


BarProp - Web APIs

BarProp
=======

The **`BarProp`** interface of the `Document Object Model` represents the web browser user interface elements that are exposed to scripts in web pages. Each of the following interface elements are represented by a `BarProp` object.

`Window.locationbar`

The browser location bar.

`Window.menubar`

The browser menu bar.

`Window.personalbar`

The browser personal bar.

`Window.scrollbars`

The browser scrollbars.

`Window.statusbar`

The browser status bar.

`Window.toolbar`

The browser toolbar.

The `BarProp` interface is not accessed directly, but via one of these elements.

Instance properties
-------------------

`BarProp.visible` Read only

A `Boolean`, which is true if the bar represented by the used interface element is visible.

Examples
--------

The following example prints a `BarProp` object to the console that represents the location bar.

```js
console.log(window.locationbar);
```

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

| Specification |
| --- |
| HTML Standard # barprop |

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

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


ConvolverNode - Web APIs

ConvolverNode
=============

The `ConvolverNode` interface is an `AudioNode` that performs a Linear Convolution on a given `AudioBuffer`, often used to achieve a reverb effect. A `ConvolverNode` always has exactly one input and one output.

**Note:** For more information on the theory behind Linear Convolution, see the Convolution article on Wikipedia.

EventTarget

AudioNode

ConvolverNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"clamped-max"` |
| Channel count | `1`, `2`, or `4` |
| Channel interpretation | `"speakers"` |

Constructor
-----------

`ConvolverNode()`

Creates a new `ConvolverNode` object instance.

Instance properties
-------------------

*Inherits properties from its parent, `AudioNode`*.

`ConvolverNode.buffer`

A mono, stereo, or 4-channel *`AudioBuffer`* containing the (possibly multichannel) impulse response used by the `ConvolverNode` to create the reverb effect.

`ConvolverNode.normalize`

A boolean that controls whether the impulse response from the buffer will be scaled by an equal-power normalization when the `buffer` attribute is set, or not.

Instance methods
----------------

*No specific method; inherits methods from its parent, `AudioNode`*.

ConvolverNode Example
---------------------

The following example shows basic usage of an AudioContext to create a convolver node.

**Note:** You will need to find an impulse response to complete the example below. See this Codepen for an applied example.

```js
let audioCtx = new window.AudioContext();

async function createReverb() {
  let convolver = audioCtx.createConvolver();

  // load impulse response from file
  let response = await fetch("path/to/impulse-response.wav");
  let arraybuffer = await response.arrayBuffer();
  convolver.buffer = await audioCtx.decodeAudioData(arraybuffer);

  return convolver;
}

// …

let reverb = await createReverb();

// someOtherAudioNode -> reverb -> destination
someOtherAudioNode.connect(reverb);
reverb.connect(audioCtx.destination);
```

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

| Specification |
| --- |
| Web Audio API # ConvolverNode |

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

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

See also
--------

* Using the Web Audio API


Presentation API - Web APIs

Presentation API
================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The Presentation API lets a user agent (such as a Web browser) effectively display web content through large presentation devices such as projectors and network-connected televisions. Supported types of multimedia devices include both displays which are wired using HDMI, DVI, or the like, or wireless, using DLNA, Chromecast, AirPlay, or Miracast.

![1-UA mode loaded the Controlling and Presenting pages together before outputting to displays. 2-UA mode loaded them separately using the Presentation Control Protocol.](/en-US/docs/Web/API/Presentation_API/presentation_mode_illustration.png)

In general, a web page uses the Presentation Controller API to specify the web content to be rendered on presentation device and initiate the presentation session. With Presentation Receiver API, the presenting web content obtains the session status. With providing both the controller page and the receiver one with a messaged-based channel, a Web developer can implement the interaction between these two pages.

Depending on the connection mechanism provided by the presentation device, any controller- and receiver page can be rendered by the same user agent, or by separated user agents.

* For 1-UA mode devices, both pages are loaded by the same user agent. However, rendering result of the receiver page will be sent to the presentation device via supported remote rendering protocol.
* For 2-UAs mode device, the receiver page is loaded directly on the presentation device. Controlling user agent communicates with presentation device via supported presentation control protocol, to control the presentation session and to transmit the message between two pages.
Interfaces
----------

`Presentation`

In controlling browsing context, the `Presentation` interface provides a mechanism to override the browser default behavior of launching presentation to external screen. In receiving browsing context, `Presentation` interface provides the access to the available presentation connections.

`PresentationRequest`

Initiates or reconnects to a presentation made by a controlling browsing context.

`PresentationAvailability`

A PresentationAvailability object is associated with available presentation displays and represents the *presentation display availability* for a presentation request.

`PresentationConnectionAvailableEvent`

The `PresentationConnectionAvailableEvent` is fired on a `PresentationRequest` when a connection associated with the object is created.

`PresentationConnection`

Each presentation connection is represented by a PresentationConnection object.

`PresentationConnectionCloseEvent`

A `PresentationConnectionCloseEvent` is fired when a presentation connection enters a `closed` state.

`PresentationReceiver`

The PresentationReceiver allows a receiving browsing context to access the controlling browsing contexts and communicate with them.

`PresentationConnectionList`

`PresentationConnectionList` represents the collection of non-terminated presentation connections. It is also a monitor for the event of new available presentation connection.

Example
-------

Example codes below highlight the usage of main features of the Presentation API: `controller.html` implements the controller and `presentation.html` implements the presentation. Both pages are served from the domain `https://example.org` (`https://example.org/controller.html` and `https://example.org/presentation.html`). These examples assume that the controlling page is managing one presentation at a time. Please refer to the comments in the code examples for further details.

### Monitor availability of presentation displays

In `controller.html`:

```html
<button id="presentBtn" style="display: none;">Present</button>
<script>
 // The Present button is visible if at least one presentation display is available
 const presentBtn = document.getElementById("presentBtn");

 // It is also possible to use relative presentation URL e.g. "presentation.html"
 const presUrls = [
 "https://example.com/presentation.html",
 "https://example.net/alternate.html",
 ];

 // Show or hide present button depending on display availability
 const handleAvailabilityChange = (available) => {
 presentBtn.style.display = available ? "inline" : "none";
 };

 // Promise is resolved as soon as the presentation display availability is known.
 const request = new PresentationRequest(presUrls);
 request
 .getAvailability()
 .then((availability) => {
 // availability.value may be kept up-to-date by the controlling UA as long
 // as the availability object is alive. It is advised for the web developers
 // to discard the object as soon as it's not needed.
 handleAvailabilityChange(availability.value);
 availability.onchange = () => {
 handleAvailabilityChange(availability.value);
 };
 })
 .catch(() => {
 // Availability monitoring is not supported by the platform, so discovery of
 // presentation displays will happen only after request.start() is called.
 // Pretend the devices are available for simplicity; or, one could implement
 // a third state for the button.
 handleAvailabilityChange(true);
 });
</script>
```

### Starting a new presentation

In `controller.html`:

```html
<script>
 presentBtn.onclick = () => {
 // Start new presentation.
 request
 .start()
 // The connection to the presentation will be passed to setConnection on success.
 .then(setConnection);
 // Otherwise, the user canceled the selection dialog or no screens were found.
 };
</script>
```

### Reconnect to a presentation

In the `controller.html` file:

```html
<button id="reconnectBtn" style="display: none;">Reconnect</button>
<script>
 const reconnect = () => {
 // read presId from localStorage if exists
 const presId = localStorage["presId"];
 // presId is mandatory when reconnecting to a presentation.
 if (presId) {
 request
 .reconnect(presId)
 // The new connection to the presentation will be passed to
 // setConnection on success.
 .then(setConnection);
 // No connection found for presUrl and presId, or an error occurred.
 }
 };
 // On navigation of the controller, reconnect automatically.
 document.addEventListener("DOMContentLoaded", reconnect);
 // Or allow manual reconnection.
 reconnectBtn.onclick = reconnect;
</script>
```

### Presentation initiation by the controlling UA

In the `controller.html` file:

```html
<script>
 navigator.presentation.defaultRequest = new PresentationRequest(presUrls);
 navigator.presentation.defaultRequest.onconnectionavailable = (evt) => {
 setConnection(evt.connection);
 };
</script>
```

Setting `presentation.defaultRequest` allows the page to specify the `PresentationRequest` to use when the controlling UA initiates a presentation.

### Monitor connection's state and exchange data

In `controller.html`:

```html
<button id="disconnectBtn" style="display: none;">Disconnect</button>
<button id="stopBtn" style="display: none;">Stop</button>
<button id="reconnectBtn" style="display: none;">Reconnect</button>
<script>
 let connection;

 // The Disconnect and Stop buttons are visible if there is a connected presentation
 const stopBtn = document.querySelector("#stopBtn");
 const reconnectBtn = document.querySelector("#reconnectBtn");
 const disconnectBtn = document.querySelector("#disconnectBtn");

 stopBtn.onclick = () => {
 connection?.terminate();
 };

 disconnectBtn.onclick = () => {
 connection?.close();
 };

 function setConnection(newConnection) {
 // Disconnect from existing presentation, if not attempting to reconnect
 if (
 connection &&
 connection !== newConnection &&
 connection.state !== "closed"
 ) {
 connection.onclose = undefined;
 connection.close();
 }

 // Set the new connection and save the presentation ID
 connection = newConnection;
 localStorage["presId"] = connection.id;

 function showConnectedUI() {
 // Allow the user to disconnect from or terminate the presentation
 stopBtn.style.display = "inline";
 disconnectBtn.style.display = "inline";
 reconnectBtn.style.display = "none";
 }

 function showDisconnectedUI() {
 disconnectBtn.style.display = "none";
 stopBtn.style.display = "none";
 reconnectBtn.style.display = localStorage["presId"] ? "inline" : "none";
 }

 // Monitor the connection state
 connection.onconnect = () => {
 showConnectedUI();

 // Register message handler
 connection.onmessage = (message) => {
 console.log(`Received message: ${message.data}`);
 };

 // Send initial message to presentation page
 connection.send("Say hello");
 };

 connection.onclose = () => {
 connection = null;
 showDisconnectedUI();
 };

 connection.onterminate = () => {
 // Remove presId from localStorage if exists
 delete localStorage["presId"];
 connection = null;
 showDisconnectedUI();
 };
 }
</script>
```

### Monitor available connection(s) and say hello

In `presentation.html`:

```js
const addConnection = (connection) => {
  connection.onmessage = (message) => {
    if (message.data === "Say hello") connection.send("hello");
  };
};

navigator.presentation.receiver.connectionList.then((list) => {
  list.connections.forEach((connection) => {
    addConnection(connection);
  });
  list.onconnectionavailable = (evt) => {
    addConnection(evt.connection);
  };
});
```

### Passing locale information with a message

In the `controller.html` file:

```html
<script>
 connection.send('{"string": "你好，世界!", "lang": "zh-CN"}');
 connection.send('{"string": "こんにちは、世界!", "lang": "ja"}');
 connection.send('{"string": "안녕하세요, 세계!", "lang": "ko"}');
 connection.send('{"string": "Hello, world!", "lang": "en-US"}');
</script>
```

In the `presentation.html` file:

```html
<script>
 connection.onmessage = (message) => {
 const messageObj = JSON.parse(message.data);
 const spanElt = document.createElement("SPAN");
 spanElt.lang = messageObj.lang;
 spanElt.textContent = messageObj.string;
 document.body.appendChild(spanElt);
 };
</script>
```

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

| Specification |
| --- |
| Presentation API # interface-presentation |

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

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

See also
--------

Presentation API polyfill contains a JavaScript polyfill of the Presentation API specification under standardization within the Second Screen Working Group at W3C. The polyfill is mostly intended for exploring how the Presentation API may be implemented on top of different presentation mechanisms.


Web Components - Web APIs

Web Components
==============

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

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

* Learn more
* See full compatibility
* Report feedback
Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.

Concepts and usage
------------------

As developers, we all know that reusing code as much as possible is a good idea. This has traditionally not been so easy for custom markup structures — think of the complex HTML (and associated style and script) you've sometimes had to write to render custom UI controls, and how using them multiple times can turn your page into a mess if you are not careful.

Web Components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.

**Custom elements**

A set of JavaScript APIs that allow you to define custom elements and their behavior, which can then be used as desired in your user interface.

**Shadow DOM**

A set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element — which is rendered separately from the main document DOM — and controlling associated functionality. In this way, you can keep an element's features private, so they can be scripted and styled without the fear of collision with other parts of the document.

**HTML templates**

The `<template>` and `<slot>` elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element's structure.

The basic approach for implementing a web component generally looks something like this:

1. Create a class in which you specify your web component functionality, using the class syntax.
2. Register your new custom element using the `CustomElementRegistry.define()` method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, what element it inherits from.
3. If required, attach a shadow DOM to the custom element using `Element.attachShadow()` method. Add child elements, event listeners, etc., to the shadow DOM using regular DOM methods.
4. If required, define an HTML template using `<template>` and `<slot>`. Again use regular DOM methods to clone the template and attach it to your shadow DOM.
5. Use your custom element wherever you like on your page, just like you would any regular HTML element.
Guides
------

Using custom elements

A guide showing how to use the features of custom elements to create simple web components, as well as looking into lifecycle callbacks and some other more advanced features.

Using shadow DOM

A guide that looks at shadow DOM fundamentals, showing how to attach a shadow DOM to an element, add to the shadow DOM tree, style it, and more.

Using templates and slots

A guide showing how to define a reusable HTML structure using `<template>` and `<slot>` elements, and then use that structure inside your web components.

Reference
---------

### Custom elements

`CustomElementRegistry`

Contains functionality related to custom elements, most notably the `CustomElementRegistry.define()` method used to register new custom elements so they can then be used in your document.

`Window.customElements`

Returns a reference to the `CustomElementRegistry` object.

Life cycle callbacks

Special callback functions defined inside the custom element's class definition, which affect its behavior:

`connectedCallback()`

Invoked when the custom element is first connected to the document's DOM.

`disconnectedCallback()`

Invoked when the custom element is disconnected from the document's DOM.

`adoptedCallback()`

Invoked when the custom element is moved to a new document.

`attributeChangedCallback()`

Invoked when one of the custom element's attributes is added, removed, or changed.

Extensions for creating custom built-in elements

The following extensions are defined:

The `is` global HTML attribute

Allows you to specify that a standard HTML element should behave like a registered custom built-in element.

The "is" option of the `Document.createElement()` method

Allows you to create an instance of a standard HTML element that behaves like a given registered custom built-in element.

CSS pseudo-classes

Pseudo-classes relating specifically to custom elements:

`:defined`

Matches any element that is defined, including built in elements and custom elements defined with `CustomElementRegistry.define()`.

`:host`

Selects the shadow host of the shadow DOM containing the CSS it is used inside.

`:host()`

Selects the shadow host of the shadow DOM containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host.

`:host-context()`

Selects the shadow host of the shadow DOM containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the DOM hierarchy.

CSS pseudo-elements

Pseudo-elements relating specifically to custom elements:

`::part`

Represents any element within a shadow tree that has a matching `part` attribute.

### Shadow DOM

`ShadowRoot`

Represents the root node of a shadow DOM subtree.

`Element` extensions

Extensions to the `Element` interface related to shadow DOM:

* The `Element.attachShadow()` method attaches a shadow DOM tree to the specified element.
* The `Element.shadowRoot` property returns the shadow root attached to the specified element, or `null` if there is no shadow root attached.

Relevant `Node` additions

Additions to the `Node` interface relevant to shadow DOM:

* The `Node.getRootNode()` method returns the context object's root, which optionally includes the shadow root if it is available.
* The `Node.isConnected` property returns a boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the `Document` object in the case of the normal DOM, or the `ShadowRoot` in the case of a shadow DOM.

`Event` extensions

Extensions to the `Event` interface related to shadow DOM:

`Event.composed`

Returns `true` if the event will propagate across the shadow DOM boundary into the standard DOM, otherwise `false`.

`Event.composedPath`

Returns the event's path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with `ShadowRoot.mode` closed.

### HTML templates

`<template>`

Contains an HTML fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using JavaScript, mainly used as the basis of custom element structures. The associated DOM interface is `HTMLTemplateElement`.

`<slot>`

A placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. The associated DOM interface is `HTMLSlotElement`.

The `slot` global HTML attribute

Assigns a slot in a shadow DOM shadow tree to an element.

`Element.assignedSlot`

A read-only attribute which returns a reference to the `<slot>` in which this element is inserted.

`Text.assignedSlot`

A read-only attribute which returns a reference to the `<slot>` in which this text node is inserted.

`Element` extensions

Extensions to the `Element` interface related to slots:

`Element.slot`

Returns the name of the shadow DOM slot attached to the element.

CSS pseudo-elements

Pseudo-elements relating specifically to slots:

`::slotted`

Matches any content that is inserted into a slot.

The `slotchange` event

Fired on an `HTMLSlotElement` instance (`<slot>` element) when the node(s) contained in that slot change.

Examples
--------

We are building up a number of examples in our web-components-examples GitHub repo. More will be added as time goes on.

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

| Specification |
| --- |
| HTML Standard # the-template-element |
| DOM Standard # interface-shadowroot |

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

### html.elements.template

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

### api.ShadowRoot

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


XRWebGLLayer - Web APIs

XRWebGLLayer
============

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The **`XRWebGLLayer`** interface of the WebXR Device API provides a linkage between the WebXR device (or simulated XR device, in the case of an inline session) and a WebGL context used to render the scene for display on the device. In particular, it provides access to the WebGL framebuffer and viewport to ease access to the context.

Although `XRWebGLLayer` is currently the only type of framebuffer layer supported by WebGL, it's entirely possible that future updates to the WebXR specification may allow for other layer types and corresponding image sources.

EventTarget

XRLayer

XRWebGLLayerConstructor
-----------

`new XRWebGLLayer()`
Experimental

Creates and returns a new `XRWebGLLayer` object for use by the specified `XRSession`, using a particular `WebGLRenderingContext` or `WebGL2RenderingContext` as the destination context.

Instance properties
-------------------

`antialias` Read only
Experimental

A Boolean value indicating whether or not the WebGL context's framebuffer supports anti-aliasing. The specific type of anti-aliasing is determined by the user agent.

`fixedFoveation`
Experimental

A number indicating the amount of foveation used by the XR compositor. Fixed Foveated Rendering (FFR) renders the edges of the eye textures at a lower resolution than the center and reduces the GPU load.

`framebuffer` Read only
Experimental

Returns a `WebGLFramebuffer` suitable for passing into the `bindFrameBuffer()` method.

`framebufferWidth` Read only
Experimental

Returns the width of the `XRWebGLLayer`'s framebuffer.

`framebufferHeight` Read only
Experimental

Returns the height of the layer's framebuffer.

`ignoreDepthValues` Read only
Experimental

A Boolean which Indicates whether or not the WebXR compositor should make use of the contents of the layer's depth buffer while compositing the scene.

Static methods
--------------

`getNativeFramebufferScaleFactor()`
Experimental

Returns the scaling factor that can be used to scale the resolution of the recommended WebGL framebuffer resolution to the rendering device's native resolution.

Instance methods
----------------

`getViewport()`
Experimental

Returns a new `XRViewport` instance representing the position, width, and height to which the WebGL context's viewport must be set to contain drawing to the area of the framebuffer designated for the specified view's contents. In this way, for example, the rendering of the left eye's point of view and of the right eye's point of view are each placed into the correct parts of the framebuffer.

Examples
--------

### Binding the layer to a WebGL context

This snippet, taken from Drawing a frame in our "Movement and motion" WebXR example, shows how the `XRWebGLLayer` is obtained from the `XRSession` object's rendering state and is then bound as the current rendering WebGL framebuffer by calling the WebGL `bindFrameBuffer()` function.

```js
let glLayer = xrSession.renderState.baseLayer;
gl.bindFrameBuffer(gl.FRAMEBUFFER, glLayer.framebuffer);
```

### Rendering every view in a frame

Each time the GPU is ready to render the scene to the XR device, the XR runtime calls the function you specified when you called the `XRSession` method `requestAnimationFrame()` to ask to render the frame.

That function receives as input an `XRFrame` which encapsulates the data needed to render the frame. This information includes the pose (an `XRViewerPose` object) that describes the position and facing direction of the viewer within the scene as well as a list of `XRView` objects, each representing one perspective on the scene. In current WebXR implementations, there will never be more than two entries in this list: one describing the position and viewing angle of the left eye and another doing the same for the right.

```js
let pose = xrFrame.getViewerPose(xrReferenceSpace);

if (pose) {
  const glLayer = xrSession.renderState.baseLayer;
  gl.bindFrameBuffer(gl.FRAMEBUFFER, glLayer.Framebffer);

  for (const view of pose.views) {
    const viewport = glLayer.getViewport(view);
    gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);

    /\* Render the view \*/
  }
}
```

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

| Specification |
| --- |
| WebXR Device API # xrwebgllayer-interface |

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

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

See also
--------

* WebXR Device API
* Getting started with WebGL
* `WebGLRenderingContext` and `WebGL2RenderingContext`
* Drawing a frame in our "Movement and motion" WebXR example


AudioContext - Web APIs

AudioContext
============

The `AudioContext` interface represents an audio-processing graph built from audio modules linked together, each represented by an `AudioNode`.

An audio context controls both the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an `AudioContext` before you do anything else, as everything happens inside a context. It's recommended to create one AudioContext and reuse it instead of initializing a new one each time, and it's OK to use a single `AudioContext` for several different audio sources and pipeline concurrently.

EventTarget

BaseAudioContext

AudioContextConstructor
-----------

`AudioContext()`

Creates and returns a new `AudioContext` object.

Instance properties
-------------------

*Also inherits properties from its parent interface, `BaseAudioContext`.*

`AudioContext.baseLatency` Read only

Returns the number of seconds of processing latency incurred by the `AudioContext` passing the audio from the `AudioDestinationNode` to the audio subsystem.

`AudioContext.outputLatency` Read only

Returns an estimation of the output latency of the current audio context.

`AudioContext.sinkId` Read only
Experimental

Returns the sink ID of the current output audio device.

Instance methods
----------------

*Also inherits methods from its parent interface, `BaseAudioContext`.*

`AudioContext.close()`

Closes the audio context, releasing any system audio resources that it uses.

`AudioContext.createMediaElementSource()`

Creates a `MediaElementAudioSourceNode` associated with an `HTMLMediaElement`. This can be used to play and manipulate audio from `<video>` or `<audio>` elements.

`AudioContext.createMediaStreamSource()`

Creates a `MediaStreamAudioSourceNode` associated with a `MediaStream` representing an audio stream which may come from the local computer microphone or other sources.

`AudioContext.createMediaStreamDestination()`

Creates a `MediaStreamAudioDestinationNode` associated with a `MediaStream` representing an audio stream which may be stored in a local file or sent to another computer.

`AudioContext.createMediaStreamTrackSource()`

Creates a `MediaStreamTrackAudioSourceNode` associated with a `MediaStream` representing an media stream track.

`AudioContext.getOutputTimestamp()`

Returns a new `AudioTimestamp` object containing two audio timestamp values relating to the current audio context.

`AudioContext.resume()`

Resumes the progression of time in an audio context that has previously been suspended/paused.

`AudioContext.setSinkId()`
Experimental

Sets the output audio device for the `AudioContext`.

`AudioContext.suspend()`

Suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process.

Events
------

`sinkchange`
Experimental

Fired when the output audio device (and therefore, the `AudioContext.sinkId`) has changed.

Examples
--------

Basic audio context declaration:

```js
const audioCtx = new AudioContext();

const oscillatorNode = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
const finish = audioCtx.destination;
// etc.
```

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

| Specification |
| --- |
| Web Audio API # AudioContext |

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

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

See also
--------

* Using the Web Audio API
* `OfflineAudioContext`


TextTrackList - Web APIs

TextTrackList
=============

The **`TextTrackList`** interface is used to represent a list of the text tracks defined by the `<track>` element, with each track represented by a separate `textTrack` object in the list.

Retrieve an instance of this object with the `textTracks` property of an `HTMLMediaElement` object.

For a given `HTMLMediaElement` object *media*, the individual tracks can be accessed using:

* `media.TextTracks[n]`, to get the n-th text track from the object's list of text tracks
* the `media.textTracks`.`getTrackById()` method

EventTarget

TextTrackListInstance properties
-------------------

*This interface also inherits properties from its parent interface, `EventTarget`.*

`length` Read only

The number of tracks in the list.

Instance methods
----------------

*This interface also inherits methods from its parent interface, `EventTarget`.*

`getTrackById()`

Returns the `TextTrack` found within the `TextTrackList` whose `id` matches the specified string. If no match is found, `null` is returned.

Events
------

`addtrack`

 Fired when a new text track has been added to the media element.
 Also available via the `onaddtrack` property.

`change`

 Fired when a text track has been made active or inactive.
 Also available via the `onchange` property.

`removetrack`

 Fired when a new text track has been removed from the media element.
 Also available via the `onremovetrack` property.

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

In addition to being able to obtain direct access to the text tracks present on a media element, `TextTrackList` lets you set event handlers on the `addtrack` and `removetrack` events, so that you can detect when tracks are added to or removed from the media element's stream.

Examples
--------

### Getting a video element's text track list

To get a media element's `TextTrackList`, use its `textTracks` property.

```js
const textTracks = document.querySelector("video").textTracks;
```

### Monitoring track count changes

In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the `addtrack` and `removetrack` events are set up.

```js
textTracks.onaddtrack = updateTrackCount;
textTracks.onremovetrack = updateTrackCount;

function updateTrackCount(event) {
  trackCount = textTracks.length;
  drawTrackCountIndicator(trackCount);
}
```

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

| Specification |
| --- |
| HTML Standard # text-track-api |

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

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


Metadata - Web APIs

Metadata
========

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

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

The **`Metadata`** interface contains information about a file system entry. This metadata includes the file's size and modification date and time.

**Note:** This interface isn't available through the global scope; instead, you obtain a `Metadata` object describing a `FileSystemEntry` using the method `FileSystemEntry.getMetadata()`.

Instance properties
-------------------

`modificationTime` Read only
Experimental

Non-standard

A `Date` object indicating the date and time the entry was modified.

`size` Read only
Experimental

Non-standard

A 64-bit unsigned integer indicating the size of the entry in bytes.

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

This feature has been removed from all specification and is not in the process of being standardized.

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemEntry`
* `FileSystemFileEntry` and `FileSystemDirectoryEntry`


HTMLTableRowElement - Web APIs

HTMLTableRowElement
===================

The **`HTMLTableRowElement`** interface provides special properties and methods (beyond the `HTMLElement` interface it also has available to it by inheritance) for manipulating the layout and presentation of rows in an HTML table.

EventTarget

Node

Element

HTMLElement

HTMLTableRowElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLTableRowElement.cells` Read only

Returns a live `HTMLCollection` containing the cells in the row. The `HTMLCollection` is live and is automatically updated when cells are added or removed.

`HTMLTableRowElement.rowIndex` Read only

Returns a `long` value which gives the logical position of the row within the entire table. If the row is not part of a table, returns `-1`.

`HTMLTableRowElement.sectionRowIndex` Read only

Returns a `long` value which gives the logical position of the row within the table section it belongs to. If the row is not part of a section, returns `-1`.

Instance methods
----------------

*Inherits methods from its parent, `HTMLElement`*.

`deleteCell(index)`

Removes the cell corresponding to `index`. If `index` is `-1`, the last cell of the row is removed. If `index` is less than `-1` or greater than the amount of cells in the collection, a `DOMException` with the value `IndexSizeError` is raised.

`insertCell(index)`

Returns an `HTMLTableCellElement` representing a new cell of the row. The cell is inserted in the collection of cells immediately before the given `index` position in the row. If `index` is `-1`, the new cell is appended to the collection. If `index` is less than `-1` or greater than the number of cells in the collection, a `DOMException` with the value `IndexSizeError` is raised.

Deprecated properties
---------------------

**Warning:** These properties have been deprecated and should no longer be used. They are documented primarily to help understand older code bases.

`HTMLTableRowElement.align`
Deprecated

A string containing an enumerated value reflecting the `align` attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, and `"center"`.

`HTMLTableRowElement.bgColor`
Deprecated

A string containing the background color of the cells. It reflects the obsolete `bgColor` attribute.

`HTMLTableRowElement.ch`
Deprecated

A string containing one single character. This character is the one to align all the cell of a column on. It reflects the `char` and default to the decimal points associated with the language, e.g. `'.'` for English, or `','` for French. This property was optional and was not very well supported.

`HTMLTableRowElement.chOff`
Deprecated

A string containing an integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by `HTMLTableRowElement.ch`. This property was optional and was not very well supported.

`HTMLTableRowElement.vAlign`
Deprecated

A string representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the `valign` attribute and can have one of the following values: `"top"`, `"middle"`, `"bottom"`, or `"baseline"`.

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

| Specification |
| --- |
| HTML Standard # htmltablerowelement |

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

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

See also
--------

* The HTML element implementing this interface: `<tr>`.


CSSTranslate - Web APIs

CSSTranslate
============

The **`CSSTranslate`** interface of the CSS\_Object\_Model#css\_typed\_object\_model represents the translate() value of the individual `transform` property in CSS. It inherits properties and methods from its parent `CSSTransformValue`.

CSSTransformComponent

CSSTranslateConstructor
-----------

`CSSTranslate()`

Creates a new `CSSTranslate` object.

Instance properties
-------------------

`x`

Returns or sets the x-axis value.

`y`

Returns or sets the y-axis value.

`z`

Returns or sets the z-axis value.

Examples
--------

To do.

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

| Specification |
| --- |
| CSS Typed OM Level 1 # csstranslate |

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

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


DeviceMotionEventAcceleration - Web APIs

DeviceMotionEventAcceleration
=============================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`DeviceMotionEventAcceleration`** interface of the Device Orientation Events provides information about the amount of acceleration the device is experiencing along all three axes.

Instance properties
-------------------

`DeviceMotionEventAcceleration.x` Read only

The amount of acceleration along the X axis.

`DeviceMotionEventAcceleration.y` Read only

The amount of acceleration along the Y axis.

`DeviceMotionEventAcceleration.z` Read only

The amount of acceleration along the Z axis.

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

| Specification |
| --- |
| DeviceOrientation Event Specification # devicemotioneventacceleration |

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

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


XRHand - Web APIs

XRHand
======

The **`XRHand`** interface is pair iterator (an ordered map) with the key being the hand joints and the value being an `XRJointSpace`.

`XRHand` is returned by `XRInputSource.hand`.

Instance properties
-------------------

`size` Read only
Experimental

Returns `25`, the size of the pair iterator.

Instance methods
----------------

 The `XRhand` object is a pair iterator. It can directly be used in a `for...of` structure. `for (const joint of myHand)` is equivalent to `for (const joint of myHand.entries())`.
 However, it's not a map-like object, so you don't have the `clear()`, `delete()`, `has()`, and `set()` methods.

`entries()`
Experimental

 Returns an iterator with the hand joints/`XRJointSpace` pairs for each element.
 See `Map.prototype.entries()` for more details.

`forEach()`
Experimental

 Runs a provided function once per each hand joint/`XRJointSpace` pair.
 See `Map.prototype.forEach()` for more details.

`get()`
Experimental

 Returns a `XRJointSpace` for a given hand joint or `undefined` if no such hand joint key is in the map.
 See `Map.prototype.get()` for more details.

`keys()`
Experimental

 Returns an iterator with all the hand joint keys.
 See `Map.prototype.keys()` for more details.

`values()`
Experimental

 Returns an iterator with all the `XRJointSpace` values.
 See `Map.prototype.values()` for more details.

Hand joints
-----------

The `XRHand` object contains the following hand joints:

![Hand](/en-US/docs/Web/API/XRHand/hand.svg)

| Hand joint | Index |
| --- | --- |
| wrist | 0 |
| thumb-metacarpal | 1 |
| thumb-phalanx-proximal | 2 |
| thumb-phalanx-distal | 3 |
| thumb-tip | 4 |
| index-finger-metacarpal | 5 |
| index-finger-phalanx-proximal | 6 |
| index-finger-phalanx-intermediate | 7 |
| index-finger-phalanx-distal | 8 |
| index-finger-tip | 9 |
| middle-finger-metacarpal | 10 |
| middle-finger-phalanx-proximal | 11 |
| middle-finger-phalanx-intermediate | 12 |
| middle-finger-phalanx-distal | 13 |
| middle-finger-tip | 14 |
| ring-finger-metacarpal | 15 |
| ring-finger-phalanx-proximal | 16 |
| ring-finger-phalanx-intermediate | 17 |
| ring-finger-phalanx-distal | 18 |
| ring-finger-tip | 19 |
| pinky-finger-metacarpal | 20 |
| pinky-finger-phalanx-proximal | 21 |
| pinky-finger-phalanx-intermediate | 22 |
| pinky-finger-phalanx-distal | 23 |
| pinky-finger-tip | 24 |

Examples
--------

### Using `XRHand` objects

```js
const wristJoint = inputSource.hand.get("wrist");
const indexFingerTipJoint = inputSource.hand.get("index-finger-tip");

for (const [joint, jointSpace] of inputSource.hand) {
  console.log(joint);
  console.log(jointSpace);
}
```

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

| Specification |
| --- |
| WebXR Hand Input Module - Level 1 # xrhand-interface |

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

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

See also
--------

* `XRInputSource.hand`