XMLHttpRequestUpload: timeout event - Web APIs

XMLHttpRequestUpload: timeout event
===================================

The **`timeout`** event is fired when progression is terminated due to preset time expiring.

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

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

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Using the `timeout` event

You can use the `timeout` event to detect an upload that stopped because it was too slow. For a complete code example that uploads a file and displays a progress bar, see the main `XMLHttpRequestUpload` page.

The timeout is set on the `XMLHttpRequest` object using the `XMLHttpRequest.timeout` property.

```js
// In case of an timeout we hide the progress bar
// Note that this event can be listened to on the xhr object too
function errorAction(event) {
  progressBar.classList.remove("visible");
  log.textContent = `Upload failed: ${event.type}`;
}
xhr.upload.addEventListener("timeout", errorAction);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-timeout |
| XMLHttpRequest Standard # handler-xhr-ontimeout |

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

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

See also
--------

* Related events: `loadstart`, `load`, `progress`, `error`, `loadend`, `abort`
* `XMLHttpRequestUpload`
* `XMLHttpRequest.timeout`


XMLHttpRequestUpload: loadend event - Web APIs

XMLHttpRequestUpload: loadend event
===================================

The **`loadend`** event is fired when a request has completed, whether successfully (after `load`) or unsuccessfully (after `abort` or `error`).

The `loadend` event is also sent when the request has been interrupted (by a `timeout`, an `abort`, or an `error`). In such cases, both the `loaded` and `total` value of the event will be 0.

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

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

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

Using the `loadend` event
-------------------------

You can use the `loadend` event to detect the (successful or not) termination of an upload. For a complete code example that uploads a file and displays a progress bar, see the main `XMLHttpRequestUpload` page.

```js
// When the upload is finished, we hide the progress bar.
xhr.upload.addEventListener("loadend", (event) => {
  progressBar.classList.remove("visible");
  if (event.loaded !== 0) {
    // Successful termination
    log.textContent = "Upload finished.";
  }
  abortButton.disabled = true;
});
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-loadend |
| XMLHttpRequest Standard # handler-xhr-onloadend |

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

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

See also
--------

* Related events: `loadstart`, `progress`, `error`, `load`, `abort`, `timeout`
* `XMLHttpRequestUpload`


CSSNamespaceRule: namespaceURI property - Web APIs

CSSNamespaceRule: namespaceURI property
=======================================

The read-only **`namespaceURI`** property of the `CSSNamespaceRule` returns a string containing the text of the URI of the given namespace.

Value
-----

A string containing a URI.

Examples
--------

The stylesheet includes a namespace as the only rule. Therefore the first `CSSRule` returned will be a `CSSNamespaceRule`. The value of the `namespaceURI` property will be `http://www.w3.org/1999/xhtml`.

```css
@namespace url(http://www.w3.org/1999/xhtml);
```

```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].namespaceURI); //http://www.w3.org/1999/xhtml
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssnamespacerule-namespaceuri |

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

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


CSSNamespaceRule: prefix property - Web APIs

CSSNamespaceRule: prefix property
=================================

The read-only **`prefix`** property of the `CSSNamespaceRule` returns a string with the name of the prefix associated to this namespace. If there is no such prefix, it returns an empty string.

Value
-----

A string containing the prefix associated to this namespace. If there is no prefix an empty string.

Examples
--------

The stylesheet includes two namespace rules. The first has no prefix the second the prefix `svg`. Two `CSSNamespaceRule` objects will be returned. The value of the `prefix` property for the first will be an empty string, for the second `svg`.

```css
@namespace url(http://www.w3.org/1999/xhtml);
@namespace svg url(http://www.w3.org/2000/svg);
```

```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].namespaceURI); // an empty string ""
console.log(myRules[1].namespaceURI); // "svg"
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssnamespacerule-prefix |

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

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


AnalyserNode: frequencyBinCount property - Web APIs

AnalyserNode: frequencyBinCount property
========================================

The **`frequencyBinCount`** read-only property of the `AnalyserNode` interface contains the total number of data points available to `AudioContext` `sampleRate`. This is half of the `value` of the `AnalyserNode.fftSize`. The two methods' indices have a linear relationship with the frequencies they represent, between 0 and the Nyquist frequency.

Value
-----

An unsigned integer, equal to the number of values that `AnalyserNode.getByteFrequencyData()` and `AnalyserNode.getFloatFrequencyData()` copy into the provided `TypedArray`.

For technical reasons related to how the Fast Fourier transform is defined, it is always half the value of `AnalyserNode.fftSize`. Therefore, it will be one of `16`, `32`, `64`, `128`, `256`, `512`, `1024`, `2048`, `4096`, `8192`, and `16384`.

Examples
--------

 The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input.
 For more complete applied examples/information, check out our Voice-change-O-matic demo.

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;

// …

analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);

canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

function draw() {
  drawVisual = requestAnimationFrame(draw);

  analyser.getByteFrequencyData(dataArray);

  canvasCtx.fillStyle = "rgb(0 0 0)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  const barWidth = (WIDTH / bufferLength) \* 2.5 - 1;
  let barHeight;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    barHeight = dataArray[i];

    canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
    canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);

    x += barWidth;
  }
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-frequencybincount |

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

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

See also
--------

* Using the Web Audio API


AnalyserNode: maxDecibels property - Web APIs

AnalyserNode: maxDecibels property
==================================

The **`maxDecibels`** property of the `AnalyserNode` interface is a double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using `getByteFrequencyData()`.

Value
-----

A double, representing the maximum decibel value for scaling the FFT analysis data, where `0` dB is the loudest possible sound, `-10` dB is a 10th of that, etc. The default value is `-30` dB.

When getting data from `getByteFrequencyData()`, any frequencies with an amplitude of `maxDecibels` or higher will be returned as `255`.

### Exceptions

`IndexSizeError` `DOMException`

Thrown if a value less than or equal to `AnalyserNode.minDecibels` is set.

Examples
--------

 The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;

// …

analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);

canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

function draw() {
  drawVisual = requestAnimationFrame(draw);

  analyser.getByteFrequencyData(dataArray);

  canvasCtx.fillStyle = "rgb(0 0 0)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  const barWidth = (WIDTH / bufferLength) \* 2.5;
  let barHeight;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    barHeight = dataArray[i];

    canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
    canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);

    x += barWidth + 1;
  }
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-maxdecibels |

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

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

See also
--------

* Using the Web Audio API


AnalyserNode: getFloatFrequencyData() method - Web APIs

AnalyserNode: getFloatFrequencyData() method
============================================

The **`getFloatFrequencyData()`** method of the `AnalyserNode` Interface copies the current frequency data into a `Float32Array` array passed into it. Each array value is a *sample*, the magnitude of the signal at a particular time.

Each item in the array represents the decibel value for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for a `48000` Hz sample rate, the last item of the array will represent the decibel value for `24000` Hz.

If you need higher performance and don't care about precision, you can use `AnalyserNode.getByteFrequencyData()` instead, which works on a `Uint8Array`.

Syntax
------

```js
getFloatFrequencyData(array)
```

### Parameters

`array`

 The `Float32Array` that the frequency domain data will be copied to. For any sample which is silent, the value is `-Infinity`.
 If the array has fewer elements than the `AnalyserNode.frequencyBinCount`, excess elements are dropped. If it has more elements than needed, excess elements are ignored.

### Return value

None (`undefined`).

Examples
--------

```js
const audioCtx = new AudioContext();
const analyser = audioCtx.createAnalyser();
// Float32Array should be the same length as the frequencyBinCount
const myDataArray = new Float32Array(analyser.frequencyBinCount);
// fill the Float32Array with data returned from getFloatFrequencyData()
analyser.getFloatFrequencyData(myDataArray);
```

### Drawing a spectrum

The following example shows basic usage of an `AudioContext` to connect a `MediaElementAudioSourceNode` to an `AnalyserNode`. While the audio is playing, we collect the frequency data repeatedly with `requestAnimationFrame()` and draw a "winamp bar graph style" to a `<canvas>` element.

For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```html
<!doctype html>
<body>
  <script>
 const audioCtx = new AudioContext();

 //Create audio source
 //Here, we use an audio file, but this could also be e.g. microphone input
 const audioEle = new Audio();
 audioEle.src = "my-audio.mp3"; //insert file name here
 audioEle.autoplay = true;
 audioEle.preload = "auto";
 const audioSourceNode = audioCtx.createMediaElementSource(audioEle);

 //Create analyser node
 const analyserNode = audioCtx.createAnalyser();
 analyserNode.fftSize = 256;
 const bufferLength = analyserNode.frequencyBinCount;
 const dataArray = new Float32Array(bufferLength);

 //Set up audio node network
 audioSourceNode.connect(analyserNode);
 analyserNode.connect(audioCtx.destination);

 //Create 2D canvas
 const canvas = document.createElement("canvas");
 canvas.style.position = "absolute";
 canvas.style.top = "0";
 canvas.style.left = "0";
 canvas.width = window.innerWidth;
 canvas.height = window.innerHeight;
 document.body.appendChild(canvas);
 const canvasCtx = canvas.getContext("2d");
 canvasCtx.clearRect(0, 0, canvas.width, canvas.height);

 function draw() {
 //Schedule next redraw
 requestAnimationFrame(draw);

 //Get spectrum data
 analyserNode.getFloatFrequencyData(dataArray);

 //Draw black background
 canvasCtx.fillStyle = "rgb(0 0 0)";
 canvasCtx.fillRect(0, 0, canvas.width, canvas.height);

 //Draw spectrum
 const barWidth = (canvas.width / bufferLength) \* 2.5;
 let posX = 0;
 for (let i = 0; i < bufferLength; i++) {
 const barHeight = (dataArray[i] + 140) \* 2;
 canvasCtx.fillStyle = `rgb(${Math.floor(barHeight + 100)} 50 50)`;
 canvasCtx.fillRect(
 posX,
 canvas.height - barHeight / 2,
 barWidth,
 barHeight / 2,
 );
 posX += barWidth + 1;
 }
 }

 draw();
 </script>
</body>
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-getfloatfrequencydata |

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

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

See also
--------

* Using the Web Audio API


AnalyserNode: fftSize property - Web APIs

AnalyserNode: fftSize property
==============================

The **`fftSize`** property of the `AnalyserNode` interface is an unsigned long value and represents the window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.

Value
-----

An unsigned integer, representing the window size of the FFT, given in number of samples. A higher value will result in more details in the frequency domain but fewer details in the amplitude domain.

Must be a power of 2 between 2^5 and 2^15, so one of: `32`, `64`, `128`, `256`, `512`, `1024`, `2048`, `4096`, `8192`, `16384`, and `32768`. Defaults to `2048`.

### Exceptions

`IndexSizeError` `DOMException`

Thrown if the value set is not a power of 2, or is outside the allowed range.

Examples
--------

 The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();

// …

analyser.fftSize = 2048;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);

// draw an oscilloscope of the current audio source

function draw() {
  drawVisual = requestAnimationFrame(draw);

  analyser.getByteTimeDomainData(dataArray);

  canvasCtx.fillStyle = "rgb(200 200 200)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  canvasCtx.lineWidth = 2;
  canvasCtx.strokeStyle = "rgb(0 0 0)";

  canvasCtx.beginPath();

  const sliceWidth = (WIDTH \* 1.0) / bufferLength;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    const v = dataArray[i] / 128.0;
    const y = (v \* HEIGHT) / 2;

    if (i === 0) {
      canvasCtx.moveTo(x, y);
    } else {
      canvasCtx.lineTo(x, y);
    }

    x += sliceWidth;
  }

  canvasCtx.lineTo(canvas.width, canvas.height / 2);
  canvasCtx.stroke();
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-fftsize |

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

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

See also
--------

* Using the Web Audio API


AnalyserNode: smoothingTimeConstant property - Web APIs

AnalyserNode: smoothingTimeConstant property
============================================

The **`smoothingTimeConstant`** property of the `AnalyserNode` interface is a double value representing the averaging constant with the last analysis frame. It's basically an average between the current buffer and the last buffer the `AnalyserNode` processed, and results in a much smoother set of value changes over time.

Value
-----

A double within the range `0` to `1` (`0` meaning no time averaging). The default value is `0.8`.

If 0 is set, there is no averaging done, whereas a value of 1 means "overlap the previous and current buffer quite a lot while computing the value", which essentially smooths the changes across `AnalyserNode.getFloatFrequencyData`/`AnalyserNode.getByteFrequencyData` calls.

In technical terms, we apply a Blackman window and smooth the values over time. The default value is good enough for most cases.

**Note:** If a value outside the range 0–1 is set, an `INDEX_SIZE_ERR` exception is thrown.

Examples
--------

 The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

If you are curious about the effect the `smoothingTimeConstant()` has, try cloning the above example and setting `analyser.smoothingTimeConstant = 0;` instead. You'll notice that the value changes are much more jarring.

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;

// …

analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);

canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

function draw() {
  drawVisual = requestAnimationFrame(draw);

  analyser.getByteFrequencyData(dataArray);

  canvasCtx.fillStyle = "rgb(0 0 0)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  const barWidth = (WIDTH / bufferLength) \* 2.5;
  let barHeight;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    barHeight = dataArray[i];

    canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
    canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);

    x += barWidth + 1;
  }
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-smoothingtimeconstant |

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

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

See also
--------

* Using the Web Audio API


AnalyserNode: getFloatTimeDomainData() method - Web APIs

AnalyserNode: getFloatTimeDomainData() method
=============================================

The **`getFloatTimeDomainData()`** method of the `AnalyserNode` Interface copies the current waveform, or time-domain, data into a `Float32Array` array passed into it. Each array value is a *sample*, the magnitude of the signal at a particular time.

Syntax
------

```js
getFloatTimeDomainData(array)
```

### Parameters

`array`

 The `Float32Array` that the time domain data will be copied to.
 If the array has fewer elements than the `AnalyserNode.fftSize`, excess elements are dropped. If it has more elements than needed, excess elements are ignored.

### Return value

None (`undefined`).

Examples
--------

 The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();

// …

analyser.fftSize = 1024;
const bufferLength = analyser.fftSize;
console.log(bufferLength);
const dataArray = new Float32Array(bufferLength);

canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

function draw() {
  drawVisual = requestAnimationFrame(draw);
  analyser.getFloatTimeDomainData(dataArray);

  canvasCtx.fillStyle = "rgb(200 200 200)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
  canvasCtx.lineWidth = 2;
  canvasCtx.strokeStyle = "rgb(0 0 0)";
  canvasCtx.beginPath();

  const sliceWidth = (WIDTH \* 1.0) / bufferLength;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    const v = dataArray[i] \* 200.0;
    const y = HEIGHT / 2 + v;

    if (i === 0) {
      canvasCtx.moveTo(x, y);
    } else {
      canvasCtx.lineTo(x, y);
    }
    x += sliceWidth;
  }

  canvasCtx.lineTo(canvas.width, canvas.height / 2);
  canvasCtx.stroke();
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-getfloattimedomaindata |

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

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

See also
--------

* Using the Web Audio API


AnalyserNode: getByteTimeDomainData() method - Web APIs

AnalyserNode: getByteTimeDomainData() method
============================================

The **`getByteTimeDomainData()`** method of the `AnalyserNode` Interface copies the current waveform, or time-domain, data into a `Uint8Array` (unsigned byte array) passed into it.

If the array has fewer elements than the `AnalyserNode.fftSize`, excess elements are dropped. If it has more elements than needed, excess elements are ignored.

Syntax
------

```js
getByteTimeDomainData(array)
```

### Parameters

`array`

 The `Uint8Array` that the time domain data will be copied to.
 If the array has fewer elements than the `AnalyserNode.fftSize`, excess elements are dropped. If it has more elements than needed, excess elements are ignored.

### Return value

None (`undefined`).

Examples
--------

 The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();

// …

analyser.fftSize = 2048;
const bufferLength = analyser.fftSize;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);

// draw an oscilloscope of the current audio source
function draw() {
  drawVisual = requestAnimationFrame(draw);
  analyser.getByteTimeDomainData(dataArray);

  canvasCtx.fillStyle = "rgb(200 200 200)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  canvasCtx.lineWidth = 2;
  canvasCtx.strokeStyle = "rgb(0 0 0)";

  const sliceWidth = (WIDTH \* 1.0) / bufferLength;
  let x = 0;

  canvasCtx.beginPath();
  for (let i = 0; i < bufferLength; i++) {
    const v = dataArray[i] / 128.0;
    const y = (v \* HEIGHT) / 2;

    if (i === 0) {
      canvasCtx.moveTo(x, y);
    } else {
      canvasCtx.lineTo(x, y);
    }

    x += sliceWidth;
  }

  canvasCtx.lineTo(WIDTH, HEIGHT / 2);
  canvasCtx.stroke();
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-getbytetimedomaindata |

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

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

See also
--------

* Using the Web Audio API


AnalyserNode: minDecibels property - Web APIs

AnalyserNode: minDecibels property
==================================

The **`minDecibels`** property of the `AnalyserNode` interface is a double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using `getByteFrequencyData()`.

Value
-----

A double, representing the minimum decibel value for scaling the FFT analysis data, where `0` dB is the loudest possible sound, `-10` dB is a 10th of that, etc. The default value is `-100` dB.

When getting data from `getByteFrequencyData()`, any frequencies with an amplitude of `minDecibels` or lower will be returned as `0`.

**Note:** If a value greater than `AnalyserNode.maxDecibels` is set, an `INDEX_SIZE_ERR` exception is thrown.

Examples
--------

 The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;

// …

analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);

canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

function draw() {
  drawVisual = requestAnimationFrame(draw);

  analyser.getByteFrequencyData(dataArray);

  canvasCtx.fillStyle = "rgb(0 0 0)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  const barWidth = (WIDTH / bufferLength) \* 2.5;
  let barHeight;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    barHeight = dataArray[i];

    canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
    canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);

    x += barWidth + 1;
  }
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-mindecibels |

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

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

See also
--------

* Using the Web Audio API


AnalyserNode: AnalyserNode() constructor - Web APIs

AnalyserNode: AnalyserNode() constructor
========================================

The **`AnalyserNode()`** constructor of the Web Audio API creates a new `AnalyserNode` object instance.

Syntax
------

```js
new AnalyserNode(context)
new AnalyserNode(context, options)
```

### Parameters

`context`

A reference to an `AudioContext` or `OfflineAudioContext`.

`options` Optional

An object with the following properties, all optional:

`fftSize`

 The desired initial size of the FFT for frequency-domain analysis.
 The default is `2048`.

`maxDecibels`

 The desired initial maximum power in dB for FFT analysis.
 The default is `-30`.

`minDecibels`

 The desired initial minimum power in dB for FFT analysis.
 The default is `-100`.

`smoothingTimeConstant`

The desired initial smoothing constant for the FFT analysis. The default is `0.8`.

`channelCount`

 Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. (See
 `AudioNode.channelCount` for more information.) Its usage and precise
 definition depend on the value of `channelCountMode`.

`channelCountMode`

 Represents an enumerated value describing the way channels must be matched between
 the node's inputs and outputs. (See `AudioNode.channelCountMode` for more
 information including default values.)

`channelInterpretation`

 Represents an enumerated value describing the meaning of the channels. This
 interpretation will define how audio up-mixing and down-mixing will happen.
 The possible values are `"speakers"` or `"discrete"`. (See
 `AudioNode.channelCountMode` for more information including default
 values.)

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-analysernode |

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

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

See also
--------

* `BaseAudioContext.createAnalyser()`, the equivalent factory method


AnalyserNode: getByteFrequencyData() method - Web APIs

AnalyserNode: getByteFrequencyData() method
===========================================

The **`getByteFrequencyData()`** method of the `AnalyserNode` interface copies the current frequency data into a `Uint8Array` (unsigned byte array) passed into it.

The frequency data is composed of integers on a scale from 0 to 255.

Each item in the array represents the decibel value for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for `48000` sample rate, the last item of the array will represent the decibel value for `24000` Hz.

If the array has fewer elements than the `AnalyserNode.frequencyBinCount`, excess elements are dropped. If it has more elements than needed, excess elements are ignored.

Syntax
------

```js
getByteFrequencyData(array)
```

### Parameters

`array`

 The `Uint8Array` that the frequency domain data will be copied to. For any sample which is silent, the value is `-Infinity`.
 If the array has fewer elements than the `AnalyserNode.frequencyBinCount`, excess elements are dropped. If it has more elements than needed, excess elements are ignored.

### Return value

None (`undefined`).

Examples
--------

The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();

// …

analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);

canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

function draw() {
  drawVisual = requestAnimationFrame(draw);

  analyser.getByteFrequencyData(dataArray);

  canvasCtx.fillStyle = "rgb(0 0 0)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  const barWidth = (WIDTH / bufferLength) \* 2.5;
  let barHeight;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    barHeight = dataArray[i];

    canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
    canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);

    x += barWidth + 1;
  }
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # dom-analysernode-getbytefrequencydata |

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

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

See also
--------

* Using the Web Audio API


CSSSkew: ax property - Web APIs

CSSSkew: ax property
====================

 The **`ax`** property of the
 `CSSSkew` interface gets and sets the angle used to distort the element
 along the x-axis (or abscissa).

Value
-----

A `CSSNumericValue`.

Examples
--------

To do

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

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

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

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


CSSSkew: CSSSkew() constructor - Web APIs

CSSSkew: CSSSkew() constructor
==============================

 The **`CSSSkew()`** constructor creates a new
 `CSSSkew` object which represents the
 `skew()` value
 of the individual `transform` property in CSS.

Syntax
------

```js
new CSSSkew(ax, ay)
```

### Parameters

`ax`

A value for the `ax` (x-axis) angle of the `CSSSkew` object to be constructed. This must be a `CSSNumericValue`.

`ay`

A value for the `ay` (y-axis) angle of the `CSSSkew` object to be constructed. This must be a `CSSNumericValue`.

Examples
--------

To do

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

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

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

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


CSSSkew: ay property - Web APIs

CSSSkew: ay property
====================

 The **`ay`** property of the
 `CSSSkew` interface gets and sets the angle used to distort the element
 along the y-axis (or ordinate).

Value
-----

A `CSSNumericValue`.

Examples
--------

To do

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

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

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

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


XRFrame: session property - Web APIs

XRFrame: session property
=========================

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

An `XRFrame` object's *read-only* **`session`** property returns the `XRSession` object that generated the frame.

Value
-----

 A `XRSession` object representing the WebXR session for which
 this `XRFrame` describes the object positions and orientations.

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

| Specification |
| --- |
| WebXR Device API # dom-xrframe-session |

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

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


XRFrame: getLightEstimate() method - Web APIs

XRFrame: getLightEstimate() method
==================================

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

The **`getLightEstimate()`** method of the `XRFrame` interface returns an `XRLightEstimate` object containing estimated lighting values for a given `XRLightProbe`.

Syntax
------

```js
getLightEstimate(lightProbe)
```

### Parameters

`lightProbe`

An `XRLightProbe` object containing the current lighting state for the frame.

### Return value

An `XRLightEstimate` object or `null` if the device cannot estimate lighting for this frame.

Examples
--------

### Getting light estimates for each frame

Given a session's `XRLightProbe`, the `getLightEstimate()` method gets an `XRLightEstimate` object containing the lighting values for each frame.

```js
const lightProbe = await xrSession.requestLightProbe();

// frame loop
function onXRFrame(time, xrFrame) {
  let lightEstimate = xrFrame.getLightEstimate(lightProbe);

  // Use light estimate data to light the scene

  // Available properties
  lightEstimate.sphericalHarmonicsCoefficients;
  lightEstimate.primaryLightDirection;
  lightEstimate.primaryLightIntensity;
}
```

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

| Specification |
| --- |
| WebXR Lighting Estimation API Level 1 # dom-xrframe-getlightestimate |

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

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

See also
--------

* `XRLightEstimate`
* `XRLightProbe`


XRFrame: getHitTestResultsForTransientInput() method - Web APIs

XRFrame: getHitTestResultsForTransientInput() method
====================================================

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

The **`getHitTestResultsForTransientInput()`** method of the `XRFrame` interface returns an array of `XRTransientInputHitTestResult` objects containing transient input hit test results for a given `XRTransientInputHitTestSource`.

Syntax
------

```js
getHitTestResultsForTransientInput(hitTestSource)
```

### Parameters

`hitTestSource`

An `XRTransientInputHitTestSource` object that contains transient input hit test subscriptions.

### Return value

An array of `XRTransientInputHitTestResult` objects.

Examples
--------

### Getting transient input hit test results

To request a transient input hit test source, start an `XRSession` with the `hit-test` session feature enabled. Next, request the hit test source with `XRSession.requestHitTestSourceForTransientInput()` and store it for later use in the frame loop. Finally, call `getHitTestResultsForTransientInput()` to obtain the result.

```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
  requiredFeatures: ["local", "hit-test"],
});

let transientHitTestSource = null;
xrSession
  .requestHitTestSourceForTransientInput({
    profile: "generic-touchscreen",
    offsetRay: new XRRay(),
  })
  .then((touchScreenHitTestSource) => {
    transientHitTestSource = touchScreenHitTestSource;
  });

// frame loop
function onXRFrame(time, xrFrame) {
  let hitTestResults = xrFrame.getHitTestResultsForTransientInput(
    transientHitTestSource,
  );
  // do things with the transient hit test results
}
```

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

| Specification |
| --- |
| WebXR Hit Test Module # dom-xrframe-gethittestresultsfortransientinput |

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

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

See also
--------

* `XRTransientInputHitTestResult`
* `XRTransientInputHitTestSource`
* `XRRay`


XRFrame: getJointPose() method - Web APIs

XRFrame: getJointPose() method
==============================

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

The **`getJointPose()`** method of the `XRFrame` interface returns an `XRJointPose` object providing the pose of a hand joint (see `XRHand`) relative to a given base space.

Syntax
------

```js
getJointPose(joint, baseSpace)
```

### Parameters

`joint`

An `XRJointSpace` specifying the hand joint space for which to obtain an `XRJointPose` describing the item's position and orientation.

`baseSpace`

An `XRSpace` to use as the base or origin for the relative position and orientation.

### Return value

 An `XRJointPose` object specifying the position and orientation of the hand joint, relative to
 the `XRSpace` indicated by `baseSpace`.

Examples
--------

### Using `getJointPose()`

Call `getJointPose()` with an `XRJointSpace` and an `XRReferenceSpace` to get an `XRJointPose` object.

```js
navigator.xr
  .requestSession({ optionalFeatures: ["hand-tracking"] })
  .then(/\* … \*/);

function renderFrame(session, frame) {
  // …

  for (const inputSource of session.inputSources) {
    if (inputSource.hand) {
      const indexFingerTipJoint = inputSource.hand.get("index-finger-tip");
      frame.getJointPose(indexFingerTipJoint, referenceSpace); // XRJointPose
    }
  }
}
```

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

| Specification |
| --- |
| WebXR Hand Input Module - Level 1 # dom-xrframe-getjointpose |

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

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

See also
--------

* `XRHand`
* `XRJointSpace`
* `XRSpace`


XRFrame: getPose() method - Web APIs

XRFrame: getPose() method
=========================

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

 The `XRFrame` method **`getPose()`** returns the relative position and
 orientation—the pose—of one `XRSpace` to that of another space. With this, you can observe the motion of objects relative to each other and to fixed locations throughout the scene.

For example, to get the position of a controller relative to the viewer's head, you would compare the controller's `gripSpace` to the `XRReferenceSpace` of type `viewer`.

Syntax
------

```js
getPose(space, baseSpace)
```

### Parameters

`space`

 An `XRSpace` specifying the space for which to obtain an
 `XRPose` describing the item's position and orientation.

`baseSpace`

 An `XRSpace` to use as the base or origin for the purposes of computing
 the relative position and orientation.

### Return value

 An `XRPose` object specifying the position and orientation, relative to
 the `XRSpace` indicated by `baseSpace`.

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

| Specification |
| --- |
| WebXR Device API # dom-xrframe-getpose |

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

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


XRFrame: fillPoses() method - Web APIs

XRFrame: fillPoses() method
===========================

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

The **`fillPoses()`** method of the `XRFrame` interface populates a `Float32Array` with the matrices of the poses relative to a given base space and returns `true` if successful for all spaces.

Syntax
------

```js
fillPoses(spaces, baseSpace, transforms)
```

### Parameters

`spaces`

An array of `XRSpace` objects for which to get the poses.

`baseSpace`

An `XRSpace` object to use as the base or origin for the relative position and orientation.

`transforms`

A `Float32Array` that is populated with the matrices of the poses relative to the given `baseSpace`.

### Return value

A boolean indicating if all of the spaces have a valid pose.

### Exceptions

`TypeError`

Thrown if the length of `spaces` multiplied by 16 is larger than the number of elements in `transforms`.

Examples
--------

### Obtaining poses for all joints of a hand

To efficiently get all poses for all 25 joints of each `XRHand`, you can use the `fillPoses()` method.

```js
let poses1 = new Float32Array(16 \* 25);
let poses2 = new Float32Array(16 \* 25);

function onXRFrame(xrFrame, renderer) {
  let hand1 = xrFrame.session.inputSources[0].hand;
  xrFrame.fillPoses(hand1.values(), renderer.referenceSpace, poses1);
  let hand2 = xrFrame.session.inputSources[1].hand;
  xrFrame.fillPoses(hand2.values(), renderer.referenceSpace, poses2);
}
```

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

| Specification |
| --- |
| WebXR Hand Input Module - Level 1 # dom-xrframe-fillposes |

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

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

See also
--------

* `XRHand`
* `XRJointSpace`
* `Float32Array`


XRFrame: getDepthInformation() method - Web APIs

XRFrame: getDepthInformation() method
=====================================

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

The **`getDepthInformation()`** method of the `XRFrame` interface returns an `XRCPUDepthInformation` object containing CPU depth information for the active and animated frame.

Syntax
------

```js
getDepthInformation(view)
```

### Parameters

`view`

An `XRView` object obtained from a viewer pose.

### Return value

An `XRCPUDepthInformation` object.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if `"depth-sensing"` is not in the list of enabled features for this `XRSession`.

`InvalidStateError` `DOMException`

Thrown if:

* the `XRFrame` is not active nor animated. Obtaining depth information is only valid within the `requestAnimationFrame()` callback.
* the session's `depthUsage` is not `"cpu-optimized"`.

Examples
--------

### Obtaining CPU depth information

```js
// Make sure to request a session with depth-sensing enabled
const session = navigator.xr.requestSession("immersive-ar", {
  requiredFeatures: ["depth-sensing"],
  depthSensing: {
    usagePreference: ["cpu-optimized", "gpu-optimized"],
    formatPreference: ["luminance-alpha", "float32"],
  },
});

// …

// Obtain depth information in an active and animated frame
function rafCallback(time, frame) {
  session.requestAnimationFrame(rafCallback);
  const pose = frame.getViewerPose(referenceSpace);
  if (pose) {
    for (const view of pose.views) {
      const depthInformation = frame.getDepthInformation(view);
      if (depthInformation) {
        // Do something with the depth information
        renderDepth(depthInformation);
      }
    }
  }
}
```

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

| Specification |
| --- |
| WebXR Depth Sensing Module # dom-xrframe-getdepthinformation |

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

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


XRFrame: fillJointRadii() method - Web APIs

XRFrame: fillJointRadii() method
================================

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

The **`fillJointRadii()`** method of the `XRFrame` interface populates a `Float32Array` with radii for a list of hand joint spaces and returns `true` if successful for all spaces.

Syntax
------

```js
fillJointRadii(jointSpaces, radii)
```

### Parameters

`jointSpaces`

An array of `XRJointSpace` objects for which to obtain the radii.

`radii`

A `Float32Array` that is populated with the radii of the `jointSpaces`.

### Return value

A boolean indicating if all of the spaces have a valid pose.

### Exceptions

`TypeError`

Thrown if the length of `jointSpaces` is larger than the number of elements in `radii`.

Examples
--------

### Obtaining radii for all joints of a hand

To efficiently get all radii for all 25 joints of each `XRHand`, you can use the `fillJointRadii()` method.

```js
let radii1 = new Float32Array(25);
let radii2 = new Float32Array(25);

function onXRFrame(xrFrame, renderer) {
  let hand1 = xrFrame.session.inputSources[0].hand;
  xrFrame.fillJointRadii(hand1.values(), radii1);
  let hand2 = xrFrame.session.inputSources[1].hand;
  xrFrame.fillJointRadii(hand2.values(), radii2);
}
```

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

| Specification |
| --- |
| WebXR Hand Input Module - Level 1 # dom-xrframe-filljointradii |

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

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

See also
--------

* `XRHand`
* `XRJointSpace`
* `Float32Array`


XRFrame: getViewerPose() method - Web APIs

XRFrame: getViewerPose() method
===============================

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

The **`getViewerPose()`** method, a member of the `XRFrame` interface, returns a `XRViewerPose` object which describes the viewer's pose (position and orientation) relative to the specified reference space.

See the `getPose()` method for a way to calculate a pose that represents the difference between two spaces.

Syntax
------

```js
getViewerPose(referenceSpace)
```

### Parameters

`referenceSpace`

 An `XRReferenceSpace` object specifying the space to use as the
 reference point or base for the computation of the viewer's current pose.

### Return value

 A `XRViewerPose` describing the viewer's position and orientation relative
 to the specified reference space.

### Exceptions

`InvalidStateError` `DOMException`

 Thrown if `getViewerPose()` was not
 called within the context of a callback to a
 session's `XRSession.requestAnimationFrame()`.

Examples
--------

 In this callback function for `requestAnimationFrame()`, the `XRViewerPose` describing the viewer's
 viewpoint on the world is obtained by calling `getViewerPose()` on the
 `XRFrame` passed into the callback.

```js
viewerPose = xrFrame.getViewerPose(xrReferenceSpace);

if (viewerPose) {
  /\* render the pose's views \*/
}
```

To see a complete example, take a look at Movement, orientation, and motion.

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

| Specification |
| --- |
| WebXR Device API # dom-xrframe-getviewerpose |

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

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


XRFrame: createAnchor() method - Web APIs

XRFrame: createAnchor() method
==============================

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

The **`createAnchor()`** method of the `XRFrame` interface creates a free-floating `XRAnchor` which will be fixed relative to the real world.

See `XRHitTestResult.createAnchor()` for creating an anchor from a hit test result that is attached to a real-world object.

Syntax
------

```js
createAnchor(pose, space)
```

### Parameters

`pose`

An `XRRigidTransform` object with the initial pose where the anchor should be created. The system will make sure that the relationship with the physical world made at this moment in time is maintained as the tracking system's understanding of the world evolves.

`space`

An `XRSpace` object the pose is relative to.

### Return value

A `Promise` resolving to an `XRAnchor` object.

Examples
--------

### Creating an anchor

```js
frame.createAnchor(anchorPose, referenceSpace).then(
  (anchor) => {
    // Do stuff with the anchor (assign objects that will be relative to this anchor)
  },
  (error) => {
    console.error(`Could not create anchor: ${error}`);
  },
);
```

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

| Specification |
| --- |
| WebXR Anchors Module # dom-xrframe-createanchor |

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

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

See also
--------

* `XRHitTestResult.createAnchor()`


XRFrame: trackedAnchors property - Web APIs

XRFrame: trackedAnchors property
================================

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

The read-only **`trackedAnchor`** property of the `XRFrame` interface returns an `XRAnchorSet` object containing all anchors still tracked in the frame.

Value
-----

An `XRAnchorSet` object.

Examples
--------

### Updating anchors

```js
for (const anchor of frame.trackedAnchors) {
  const pose = frame.getPose(anchor.anchorSpace, referenceSpace);
}
```

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

| Specification |
| --- |
| WebXR Anchors Module # dom-xrframe-trackedanchors |

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

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


XRFrame: getHitTestResults() method - Web APIs

XRFrame: getHitTestResults() method
===================================

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

The **`getHitTestResults()`** method of the `XRFrame` interface returns an array of `XRHitTestResult` objects containing hit test results for a given `XRHitTestSource`.

Syntax
------

```js
getHitTestResults(hitTestSource)
```

### Parameters

`hitTestSource`

An `XRHitTestSource` object that contains hit test subscriptions.

### Return value

An array of `XRHitTestResult` objects.

Examples
--------

### Getting hit test results

To request a hit test source, start an `XRSession` with the `hit-test` session feature enabled. Next, request a the hit test source with `XRSession.requestHitTestSource()` and store it for later use in the frame loop. Finally, call `getHitTestResults()` to obtain the result.

```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
  requiredFeatures: ["local", "hit-test"],
});
let hitTestSource = null;
xrSession
  .requestHitTestSource({
    space: viewerSpace, // obtained from xrSession.requestReferenceSpace("viewer");
    offsetRay: new XRRay({ y: 0.5 }),
  })
  .then((viewerHitTestSource) => {
    hitTestSource = viewerHitTestSource;
  });
// frame loop
function onXRFrame(time, xrFrame) {
  let hitTestResults = xrFrame.getHitTestResults(hitTestSource);
  // do things with the hit test results
}
```

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

| Specification |
| --- |
| WebXR Hit Test Module # dom-xrframe-gethittestresults |

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

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

See also
--------

* `XRHitTestResult`
* `XRHitTestSource`
* `XRRay`


RTCRtpScriptTransform: RTCRtpScriptTransform() constructor - Web APIs

RTCRtpScriptTransform: RTCRtpScriptTransform() constructor
==========================================================

The **`RTCRtpScriptTransform()`** constructor creates a new `RTCRtpScriptTransform` object.

Constructing the `RTCRtpScriptTransform` creates a counterpart `RTCRtpScriptTransformer` in the specified worker, along with passed options (if any). Objects in the third parameter to the constructor are transferred.

 The `rtctransform` event is then fired at the worker global object.
 Worker code can use the `event.transformer` property to get the counterpart `RTCRtpScriptTransformer`, and `event.transformer.options` is used to get the options.

Note that the options are primarily used to inform the worker whether the transformer is processing incoming or outgoing frames, so that it can apply an appropriate transform.

Syntax
------

```js
new RTCRtpScriptTransform(worker)
new RTCRtpScriptTransform(worker, options)
new RTCRtpScriptTransform(worker, options, transfer)
```

### Parameters

`worker`

A `Worker`, which will define code for one or more WebRTC transform streams.

`options` Optional

 An arbitrary object that will be made available in the worker.
 This is most commonly used to inform the worker whether it injected into the WebRTC sender or receiver pipeline, and hence which transform should be applied.
 However it may also be used to send any other object, such as a `MessagePort` for communicating dynamically with the transformer.

`transfer` Optional

 An optional array of transferable objects that will be transferred to the worker.
 After transfer, these objects are unusable in the main thread.

### Exceptions

`DataCloneError` `DOMException`

Thrown if an object in `transfer` cannot be transferred.

Examples
--------

 The first example below shows construction of a `RTCRtpScriptTransform` that is then assigned to a `RTCRtpSender.transform`.
 The constructor takes an optional object with the property `name` and `senderTransform`.
 The worker can use this option to understand when it is transforming encoded frames from the encoder (rather than incoming frames from the packetizer).

```js
// Create a worker containing a TransformStream
const worker = new Worker("worker.js");
videoSender.transform = new RTCRtpScriptTransform(worker, {
  name: "senderTransform",
});
```

 Any property name and value can be used in the options, as long as they can be serialized (and transferred if specified in the last constructor parameter).
 The code below transfers the second port of a `MessageChannel` to the worker, which we might do in order to dynamically update transform code with (say) a new encryption key.

```js
// Create a worker containing a TransformStream
const worker = new Worker("worker.js");
const channel = new MessageChannel();

const transform = new RTCRtpScriptTransform(
  worker,
  { purpose: "encrypt", port: channel.port2 },
  [channel.port2],
);
```

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

| Specification |
| --- |
| WebRTC Encoded Transform # dom-rtcrtpscripttransform-rtcrtpscripttransform |

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

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

See also
--------

* Using WebRTC Encoded Transforms
* `RTCRtpSender.transform`
* `RTCRtpReceiver.transform`


CSSStyleDeclaration: parentRule property - Web APIs

CSSStyleDeclaration: parentRule property
========================================

 The **CSSStyleDeclaration.parentRule** read-only
 property returns a `CSSRule` that is the parent of this style
 block, e.g. a `CSSStyleRule` representing the style for a CSS
 selector.

Value
-----

 The CSS rule that contains this declaration block or `null` if this
 `CSSStyleDeclaration` is not attached to a `CSSRule`.

Examples
--------

 The following JavaScript code gets the parent CSS style rule from a
 `CSSStyleDeclaration`:

```js
const declaration = document.styleSheets[0].rules[0].style;
const rule = declaration.parentRule;
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-parentrule |

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

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


CSSStyleDeclaration: cssFloat property - Web APIs

CSSStyleDeclaration: cssFloat property
======================================

The **`cssFloat`** property of the `CSSStyleDeclaration` interface returns the result of invoking `CSSStyleDeclaration.getPropertyValue()` with `float` as an argument.

When setting, it invokes `CSSStyleDeclaration.setProperty()` with `float` as the first argument, and the given value as the second argument. The given value must be a valid value for the `float` property.

Value
-----

A string.

Example
-------

In the below example, the stylesheet contains a single rule for `.box`, which has the `float` property with a value of `left`. This value will be returned by `cssFloat`. We then set the value to "right" using `cssFloat`, and return the new value.

```css
.box {
  float: left;
  inline-size: 300px;
}
```

```js
let myRules = document.styleSheets[0].cssRules;
let rule = myRules[0];
console.log(rule.style.cssFloat); // "left"
rule.style.cssFloat = "right";
console.log(rule.style.cssFloat); //right
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-cssfloat |

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

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


CSSStyleDeclaration: cssText property - Web APIs

CSSStyleDeclaration: cssText property
=====================================

The **`cssText`** property of the `CSSStyleDeclaration` interface returns or sets the text of the element's **inline** style declaration only.

To be able to set a **stylesheet** rule dynamically, see Using dynamic styling information.

Not to be confused with stylesheet style-rule `CSSRule.cssText`.

Value
-----

A string containing the text of the element's inline style declaration.

Example
-------

```html
<span id="s1" style="color: red;"> Some text </span>

<script>
 const elem = document.getElementById("s1");
 alert(elem.style.cssText); // "color: red;"
</script>
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-csstext |

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

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


CSSStyleDeclaration: removeProperty() method - Web APIs

CSSStyleDeclaration: removeProperty() method
============================================

 The **`CSSStyleDeclaration.removeProperty()`** method interface
 removes a property from a CSS style declaration object.

Syntax
------

```js
removeProperty(property)
```

### Parameters

* `property`
    + A string representing the property name to be removed. Multi-word property names are hyphenated (kebab-case) and not camel-cased.
### Return value

A string equal to the value of the CSS property before it was removed.

### Exceptions

`NoModificationAllowedError` `DOMException`

Thrown when the property or declaration block is read-only.

Examples
--------

 The following JavaScript code removes the `background-color` CSS property
 from a selector rule:

```js
const declaration = document.styleSheets[0].rules[0].style;
const oldValue = declaration.removeProperty("background-color");
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-removeproperty |

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

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


CSSStyleDeclaration: length property - Web APIs

CSSStyleDeclaration: length property
====================================

 The read-only property returns an integer that represents the
 number of style declarations in this CSS declaration block.

Value
-----

 An integer that provides the number of styles explicitly set on the parent of
 the instance.

Examples
--------

The following gets the number of explicitly set styles on the following HTML element:

```html
<div
 id="div1"
 style="margin: 0 10px; background-color: #CA1; font-family: monospace"></div>
```

JavaScript code:

```js
const myDiv = document.getElementById("div1");
const divStyle = myDiv.style;
const len = divStyle.length; // 6
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-length |

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

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


CSSStyleDeclaration: item() method - Web APIs

CSSStyleDeclaration: item() method
==================================

 The `CSSStyleDeclaration.item()`
 method interface returns a CSS property name from a `CSSStyleDeclaration`
 by index.

 This method doesn't throw exceptions as long as you provide
 arguments; the empty string is returned if the index is out of range and a
 `TypeError` is thrown if no argument is provided.

Syntax
------

```js
item(index)
```

### Parameters

`index`

The index of the node to be fetched. The index is zero-based.

### Return value

A string that is the name of the CSS property at the specified index.

JavaScript has a special simpler syntax for obtaining an item from a NodeList by index:

```js
const propertyName = style[index];
```

### Exceptions

`TypeError`

Thrown if no argument is provided.

Examples
--------

```js
const style = document.getElementById("div1").style;
const propertyName = style.item(1); // or style[1] - returns the second style listed
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-item |

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

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


CSSStyleDeclaration: getPropertyValue() method - Web APIs

CSSStyleDeclaration: getPropertyValue() method
==============================================

 The **CSSStyleDeclaration.getPropertyValue()** method interface returns a
 string containing the value of a specified CSS property.

Syntax
------

```js
getPropertyValue(property)
```

### Parameters

`property`

A string representing the property name (in hyphen case) to be checked.

### Return value

A string containing the value of the property. If not set, returns the empty string.

Examples
--------

 The following JavaScript code queries the value of the `margin` property in
 a CSS selector rule:

```js
const declaration = document.styleSheets[0].cssRules[0].style;
const value = declaration.getPropertyValue("margin"); // "1px 2px"
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-getpropertyvalue |

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

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


CSSStyleDeclaration: setProperty() method - Web APIs

CSSStyleDeclaration: setProperty() method
=========================================

 The
 **`CSSStyleDeclaration.setProperty()`** method interface sets
 a new value for a property on a CSS style declaration object.

Syntax
------

```js
setProperty(propertyName, value)
setProperty(propertyName, value, priority)
```

### Parameters

`propertyName`

A string representing the CSS property name (hyphen case) to be modified.

`value` Optional

 A string containing the new property value. If not specified, treated
 as the empty string.

**Note:** `value` must not contain `"!important"`, that should be set using the `priority` parameter.

`priority` Optional

 A string allowing the "important" CSS priority to be set. If not
 specified, treated as the empty string. The following values are accepted:

* String value `"important"`
* Keyword `undefined`
* String empty value `""`

### Return value

None (`undefined`).

### Exceptions

`NoModificationAllowedError` `DOMException`

Thrown if the property or declaration block is read only.

Alternative usage
-----------------

 If `priority` can be omitted, JavaScript has a special simpler
 syntax for setting a CSS property on a style declaration object:

```js
style.cssPropertyName = "value";
```

Examples
--------

 In this example we have three buttons, which can be pressed to dynamically alter our
 box paragraph's border, background color, and text color to random values (see the live
 example at the end of this section).

 We know that the rule we want to alter to do this is contained inside the second
 stylesheet applied to the page, so we grab a reference to it using
 `document.styleSheets[1]`.
 We then loop through the different rules contained inside the stylesheet, which are
 contained in the array found at
 `stylesheet.cssRules`;
 for each one, we check whether its
 `CSSStyleRule.selectorText`
 property is equal to the selector `.box p`, which indicates it is the one we
 want.

 If so, we store a reference to this `CSSStyleRule` object in a variable. We
 then use three functions to generate random values for the properties in question, and
 update the rule with these values. In each case, this is done with the
 `setProperty()` method, for example `boxParaRule.style.setProperty('border', newBorder);`.

### HTML

```html
<div class="controls">
  <button class="border">Border</button>
  <button class="bgcolor">Background</button>
  <button class="color">Text</button>
</div>
<div class="box">
  <p>Box</p>
</div>
```

### CSS

```css
html {
  background: orange;
  font-family: sans-serif;
  height: 100%;
}

body {
  height: inherit;
  width: 80%;
  min-width: 500px;
  max-width: 1000px;
  margin: 0 auto;
}

.controls {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

div button {
  flex: 1;
  margin: 20px;
  height: 30px;
  line-height: 30px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100% - 70px);
}

.box p {
  width: 50%;
  text-align: center;
  font-weight: bold;
  font-size: 40px;
  height: 150px;
  line-height: 150px;
  background: red;
  border: 5px solid purple;
  color: white;
  transition: all 1s;
}
```

### JavaScript

```js
const borderBtn = document.querySelector(".border");
const bgColorBtn = document.querySelector(".bgcolor");
const colorBtn = document.querySelector(".color");
const box = document.querySelector(".box");

function random(min, max) {
  const num = Math.floor(Math.random() \* (max - min)) + min;
  return num;
}

function randomColor() {
  return `rgb(${random(0, 255)} ${random(0, 255)} ${random(0, 255)})`;
}

const stylesheet = document.styleSheets[1];
const boxParaRule = [...stylesheet.cssRules].find(
  (r) => r.selectorText === ".box p",
);

function setRandomBorder() {
  const newBorder = `${random(1, 50)}px solid ${randomColor()}`;
  boxParaRule.style.setProperty("border", newBorder);
}

function setRandomBgColor() {
  const newBgColor = randomColor();
  boxParaRule.style.setProperty("background-color", newBgColor);
}

function setRandomColor() {
  const newColor = randomColor();
  boxParaRule.style.setProperty("color", newColor);
}

borderBtn.addEventListener("click", setRandomBorder);
bgColorBtn.addEventListener("click", setRandomBgColor);
colorBtn.addEventListener("click", setRandomColor);
```

### Result

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-setproperty |

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

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


CSSStyleDeclaration: getPropertyCSSValue() method - Web APIs

CSSStyleDeclaration: getPropertyCSSValue() method
=================================================

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

 The **CSSStyleDeclaration.getPropertyCSSValue()**
 method interface returns a `CSSValue` containing the CSS value for a
 property. Note that it returns `null` if the property name is a
 shorthand property.

**Note:** This interface was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do
 not implement it.

To achieve your purpose, you can use:

* `CSSStyleDeclaration.getPropertyValue()` of the untyped CSS Object Model, widely supported, or
* `Element.computedStyleMap()` of the modern CSS Typed Object Model API, less supported and considered experimental.

Syntax
------

```js
getPropertyCSSValue(property)
```

### Parameters

`property`

A string representing the property name to be retrieved.

### Return value

A `CSSValue` containing the CSS value for a property. If none exists, returns `null`.

Examples
--------

 The following JavaScript code gets an object containing the computed RGB values of
 the `color` CSS property:

```js
const style = window.getComputedStyle(elem, null);
const rgbObj = style.getPropertyCSSValue("color").getRGBColorValue();
```

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

 This feature was originally defined in the DOM Style Level 2 specification, but has been dropped from any
 standardization effort since then.

It has been superseded by a modern, but incompatible, CSS Typed Object Model API that is now on the standard track.

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

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


CSSStyleDeclaration: getPropertyPriority() method - Web APIs

CSSStyleDeclaration: getPropertyPriority() method
=================================================

 The **CSSStyleDeclaration.getPropertyPriority()** method interface returns
 a string that provides all explicitly set priorities on the CSS
 property.

Syntax
------

```js
getPropertyPriority(property)
```

### Parameters

`property`

A string representing the property name to be checked.

### Return value

 A string that represents the priority (e.g. `"important"`) if one exists.
 If none exists, returns the empty string.

Examples
--------

 The following JavaScript code checks whether `margin` is marked as important
 in a CSS selector rule:

```js
const declaration = document.styleSheets[0].cssRules[0].style;
const isImportant = declaration.getPropertyPriority("margin") === "important";
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstyledeclaration-getpropertypriority |

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

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


HTMLMeterElement: labels property - Web APIs

HTMLMeterElement: labels property
=================================

 The **`HTMLMeterElement.labels`** read-only property returns a
 `NodeList` of the `<label>` elements associated with the
 `<meter>` element.

Value
-----

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

Examples
--------

### HTML

```html
<label id="label1" for="test">Label 1</label>
<meter id="test" min="0" max="100" value="70">70</meter>
<label id="label2" for="test">Label 2</label>
```

### JavaScript

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

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

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

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

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


GPUCommandBuffer: label property - Web APIs

GPUCommandBuffer: label property
================================

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

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

This can be set by providing a `label` property in the descriptor object passed into the originating `GPUCommandEncoder.finish()` call, or you can get and set it directly on the `GPUCommandBuffer` object.

Value
-----

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

Examples
--------

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

```js
const commandBuffer = commandEncoder.finish();
commandBuffer.label = "mycommandbuffer";
console.log(commandBuffer.label); // "mycommandbuffer";
```

Setting a label via the originating `GPUCommandEncoder.finish()` call, and then getting it via `GPUCommandBuffer.label`:

```js
const commandBuffer = commandEncoder.finish({
  label: "mycommandbuffer",
});

console.log(commandBuffer.label); // "mycommandbuffer";
```

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

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

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

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

See also
--------

* The WebGPU API


IDBDatabase: versionchange event - Web APIs

IDBDatabase: versionchange event
================================

 The `versionchange` event is fired when a database structure change (`upgradeneeded` event send on an `IDBOpenDBRequest` or `IDBFactory.deleteDatabase`) was requested elsewhere (most probably in
 another window/tab on the same computer).

Syntax
------

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

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

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

A generic `Event`.

Examples
--------

This example opens a database and, on success, adds a listener to `versionchange`:

```js
// Open the database
const dBOpenRequest = window.indexedDB.open("Nonexistent", 4);

dBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;
  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain
  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
};

dBOpenRequest.addEventListener("success", (event) => {
  const db = event.target.result;
  db.addEventListener("versionchange", (event) => {
    console.log("The version of this database has changed");
  });
});
```

The same example, using the `onversionchange` event handler property:

```js
// Open the database
const dBOpenRequest = window.indexedDB.open("Nonexistent", 4);

dBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;
  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain
  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
};

dBOpenRequest.onsuccess = (event) => {
  const db = event.target.result;
  db.onversionchange = (event) => {
    console.log("The version of this database has changed");
  };
};
```

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

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

See also
--------

* Using IndexedDB


IDBDatabase: transaction() method - Web APIs

IDBDatabase: transaction() method
=================================

 The **`transaction`** method of the `IDBDatabase` interface immediately
 returns a transaction object (`IDBTransaction`) containing the
 `IDBTransaction.objectStore` method, which you can use to access your
 object store.

**Note:** This feature is available in Web Workers

Syntax
------

```js
transaction(storeNames)
transaction(storeNames, mode)
transaction(storeNames, mode, options)
```

### Parameters

`storeNames`

 The names of object stores that are in the scope of the new transaction, declared as
 an array of strings. Specify only the object stores that you need to access.
 If you need to access only one object store, you can specify its name as a string.
 Therefore the following lines are equivalent:

```js
db.transaction(["my-store-name"]);
db.transaction("my-store-name");
```

 If you need to access all object stores in the database, you can use the property
 `IDBDatabase.objectStoreNames`:

```js
const transaction = db.transaction(db.objectStoreNames);
```

Passing an empty array will throw an exception.

`mode` Optional

 The types of access that can be performed in the transaction. Transactions are
 opened in one of three modes: `readonly`, `readwrite` and
 `readwriteflush` (non-standard, Firefox-only.) `versionchange`
 mode can't be specified here. If you don't provide the parameter, the default access
 mode is `readonly`. To avoid slowing things down, don't open a
 `readwrite` transaction unless you actually need to write into the
 database.

 If you need to open the object store in `readwrite` mode to change data,
 you would use the following:

```js
const transaction = db.transaction("my-store-name", "readwrite");
```

 As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to
 increase performance (see Firefox bug 1112702), which is the same behavior as other
 IndexedDB-supporting browsers. Previously in a `readwrite` transaction, a
 `complete` event was fired only when all data was guaranteed
 to have been flushed to disk. In Firefox 40+ the `complete` event is
 fired after the OS has been told to write the data but potentially before that data
 has actually been flushed to disk. The `complete` event may thus be
 delivered quicker than before, however, there exists a small chance that the entire
 transaction will be lost if the OS crashes or there is a loss of system power before
 the data is flushed to disk. Since such catastrophic events are rare most consumers
 should not need to concern themselves further.

**Note:** In Firefox, if you wish to ensure durability for some
 reason (e.g. you're storing critical data that cannot be recomputed later) you can
 force a transaction to flush to disk before delivering the `complete`
 event by creating a transaction using the experimental (non-standard)
 `readwriteflush` mode (see `IDBDatabase.transaction`.)
 This is currently experimental, and can only be used if the
 `dom.indexedDB.experimental` pref is set to `true` in
 `about:config`.

`options` Optional

Dictionary of other options. Available options are:

`durability`

`"default"`, `"strict"`, or
 `"relaxed"`. The default is `"default"`. Using
 `"relaxed"` provides better performance, but with fewer guarantees. Web
 applications are encouraged to use `"relaxed"` for ephemeral data such
 as caches or quickly changing records, and `"strict"` in cases where
 reducing the risk of data loss outweighs the impact to performance and power.

### Return value

An `IDBTransaction` object.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `close()` method has previously been called on this `IDBDatabase` instance.

`NotFoundError` `DOMException`

Thrown if an object store specified in the 'storeNames' parameter has been deleted or removed.

`TypeError`

Thrown if the value for the `mode` parameter is invalid.

`InvalidAccessError` `DOMException`

Thrown if the function was called with an empty list of store names.

Examples
--------

 In this example we open a database connection, then use transaction() to open a
 transaction on the database. For a complete example, see our
 To-do Notifications app (view example live).

```js
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the displayData() function to populate the task list with
  // all the to-do list data already in the IDB
  displayData();
};

// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");

// report on the success of opening the transaction
transaction.oncomplete = (event) => {
  note.innerHTML +=
    "<li>Transaction completed: database modification finished.</li>";
};

transaction.onerror = (event) => {
  note.innerHTML +=
    "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};

// you would then go on to do something to this database
// via an object store
const objectStore = transaction.objectStore("toDoList");
// etc.
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbdatabase-transaction③ |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBDatabase: close() method - Web APIs

IDBDatabase: close() method
===========================

 The **`close()`** method of the `IDBDatabase`
 interface returns immediately and closes the connection in a separate thread.

 The connection is not actually closed until all transactions created using this
 connection are complete. No new transactions can be created for this connection once
 this method is called. Methods that create transactions throw an exception if a closing
 operation is pending.

**Note:** This feature is available in Web Workers

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4); // opening a database.

// Create event handlers for both success and failure of
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  db = DBOpenRequest.result;

  // now let's close the database again!
  db.close();
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbdatabase-close② |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBDatabase: close event - Web APIs

IDBDatabase: close event
========================

The `close` event is fired on `IDBDatabase` when the database connection is unexpectedly closed. This could happen, for example, if the underlying storage is removed or if the user clears the database in the browser's history preferences.

Note that it is not fired if the database connection is closed normally using `IDBDatabase.close()`.

Syntax
------

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

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

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

A generic `Event`.

Examples
--------

This example opens a database and listens for the `close` event:

```js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);

dBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain
  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
};

dBOpenRequest.onsuccess = (event) => {
  const db = dBOpenRequest.result;
  db.addEventListener("close", () => {
    console.log("Database connection closed");
  });
};
```

The same example, using the `onclose` property instead of `addEventListener()`:

```js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);

dBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain
  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
};

dBOpenRequest.onsuccess = (event) => {
  const db = dBOpenRequest.result;
  db.onclose = () => {
    console.log("Database connection closed");
  };
};
```

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

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

See also
--------

* Using IndexedDB


IDBDatabase: deleteObjectStore() method - Web APIs

IDBDatabase: deleteObjectStore() method
=======================================

 The **`deleteObjectStore()`** method of the
 `IDBDatabase` interface destroys the object store with the given name in
 the connected database, along with any indexes that reference it.

 As with `IDBDatabase.createObjectStore`, this method can be called
 *only* within a `versionchange`
 transaction.

**Note:** This feature is available in Web Workers

Syntax
------

```js
deleteObjectStore(name)
```

### Parameters

`name`

 The name of the object store you want to delete. Names are
 case sensitive.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the method was not called from a `versionchange` transaction callback.

`TransactionInactiveError` `DOMException`

Thrown if a request is made on a source database that doesn't exist (E.g. has been deleted or removed.)

`NotFoundError` `DOMException`

Thrown when trying to delete an object store that does not exist.

Examples
--------

```js
const dbName = "sampleDB";
const dbVersion = 2;
const request = indexedDB.open(dbName, dbVersion);

request.onupgradeneeded = (event) => {
  const db = request.result;
  if (event.oldVersion < 1) {
    db.createObjectStore("store1");
  }

  if (event.oldVersion < 2) {
    db.deleteObjectStore("store1");
    db.createObjectStore("store2");
  }

  // etc. for version < 3, 4…
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbdatabase-deleteobjectstore① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBDatabase: version property - Web APIs

IDBDatabase: version property
=============================

 The **`version`** property of the `IDBDatabase`
 interface is a 64-bit integer
 that contains the version of the connected database.
 When a database is first created, this attribute is an empty string.

**Note:** This feature is available in Web Workers

Value
-----

An integer containing the version of the connected database.

Examples
--------

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database
// being opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable. This is used a lot below
  db = DBOpenRequest.result;

  // This line will log the version of the connected database, which should be "4"
  console.log(db.version);
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbdatabase-version① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBDatabase: objectStoreNames property - Web APIs

IDBDatabase: objectStoreNames property
======================================

 The **`objectStoreNames`** read-only property of the
 `IDBDatabase` interface is a `DOMStringList` containing a
 list of the names of the object stores currently in the connected database.

**Note:** This feature is available in Web Workers

Value
-----

 A `DOMStringList` containing a list of
 the names of the object stores currently
 in the connected database.

Examples
--------

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable. This is used a lot below
  db = DBOpenRequest.result;

  // This line will log the names of the object stores of the connected database, which should be
  // an object that looks like { ['my-store-name'] }
  console.log(db.objectStoreNames);
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbdatabase-objectstorenames① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBDatabase: name property - Web APIs

IDBDatabase: name property
==========================

 The **`name`** read-only property of the
 `IDBDatabase` interface is a string that contains the
 name of the connected database.

**Note:** This feature is available in Web Workers

Value
-----

A string containing the name of the connected database.

Examples
--------

 This example shows a database connection being opened, the resulting
 `IDBDatabase` object being stored in a db variable, and the name property
 then being logged. For a full example, see our
 To-do Notifications
 app (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being
// opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable. This is used a lot below
  db = DBOpenRequest.result;

  // This line will log the name of the database, which should be "toDoList"
  console.log(db.name);
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbdatabase-name① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).