recursal/MDN huggingface dataset:
AudioTrackList: change event
============================

The `change` event is fired when an audio track is enabled or disabled, for example by changing the track's `enabled` property.

This event is not cancelable and does not bubble.

Syntax
------

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


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

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

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

A generic `Event`.

Examples
--------

Using `addEventListener()`:


```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.addEventListener("change", (event) => {
  console.log(`'${event.type}' event fired`);
});

// changing the value of `enabled` will trigger the `change` event
const toggleTrackButton = document.querySelector(".toggle-track");
toggleTrackButton.addEventListener("click", () => {
  const track = videoElement.audioTracks[0];
  track.enabled = !track.enabled;
});
```


Using the `onchange` event handler property:


```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.onchange = (event) => {
  console.log(`'${event.type}' event fired`);
};

// changing the value of `enabled` will trigger the `change` event
const toggleTrackButton = document.querySelector(".toggle-track");
toggleTrackButton.addEventListener("click", () => {
  const track = videoElement.audioTracks[0];
  track.enabled = !track.enabled;
});
```

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

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

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

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

See also
--------

* Related events: `addtrack`, `removetrack`
* This event on `VideoTrackList` targets: `change`
* Media Capture and Streams API
* WebRTC API
AudioTrackList: length property
===============================

 The read-only **`AudioTrackList`**
 property **`length`** returns the number of entries in the
 `AudioTrackList`, each of which is an `AudioTrack`
 representing one audio track in the media element. A value of 0 indicates that
 there are no audio tracks in the media.

Value
-----

 A number indicating how many audio tracks are included in the
 `AudioTrackList`. Each track can be accessed by treating the
 `AudioTrackList` as an array of objects of type `AudioTrack`.

Examples
--------

 This snippet gets the number of audio tracks in the first `<video>`
 element found in the DOM by `querySelector()`.


```js
const videoElem = document.querySelector("video");
let numAudioTracks = 0;

if (videoElem.audioTracks) {
  numAudioTracks = videoElem.audioTracks.length;
}
```


 Note that this sample checks to be sure `HTMLMediaElement.audioTracks` is
 defined, to avoid failing on browsers without support for `AudioTrack`.

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

| Specification |
| --- |
| HTML Standard # dom-audiotracklist-length-dev |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
AudioTrackList: removetrack event
=================================

The `removetrack` event is fired when a track is removed from an `AudioTrackList`.

Syntax
------

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


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

onremovetrack = (event) => { }
```

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

A `TrackEvent`. Inherits from `Event`.

Event

TrackEventEvent properties
----------------

*`TrackEvent` is based on `Event`, so properties of `Event` are also available on `TrackEvent` objects.*

`track` Read only 

The DOM track object the event is in reference to. If not `null`, this is always an object of one of the media track types: `AudioTrack`, `VideoTrack`, or `TextTrack`).

Description
-----------

### Trigger

 The `removetrack` event is called whenever a track is removed from the media
 element whose audio tracks are represented by the `AudioTrackList` object.

This event is not cancelable and does not bubble.

### Use cases

You can use this event to react to a new audio track becoming unavailable. You may want to update your UI elements to disallow for user selection of the removed audio track, for example.

Examples
--------

Using `addEventListener()`:


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

videoElement.audioTracks.addEventListener("removetrack", (event) => {
  console.log(`Audio track: ${event.track.label} removed`);
});
```


Using the `onremovetrack` event handler property:


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

videoElement.audioTracks.onremovetrack = (event) => {
  console.log(`Audio track: ${event.track.label} removed`);
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-removetrack |
| HTML Standard # handler-tracklist-onremovetrack |

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

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

See also
--------

* Related events: `addtrack`, `change`
* This event on `VideoTrackList` targets: `removetrack`
* This event on `MediaStream` targets: `removetrack`
* Media Capture and Streams API
* WebRTC
AudioTrackList: addtrack event
==============================

The `addtrack` event is fired when a track is added to an `AudioTrackList`.

Syntax
------

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


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

onaddtrack = (event) => { }
```

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

A `TrackEvent`. Inherits from `Event`.

Event

TrackEventEvent properties
----------------

*`TrackEvent` is based on `Event`, so properties of `Event` are also available on `TrackEvent` objects.*

`track` Read only 

The DOM track object the event is in reference to. If not `null`, this is always an object of one of the media track types: `AudioTrack`, `VideoTrack`, or `TextTrack`).

Description
-----------

### Trigger

 The `addtrack` event is called whenever a new track is added to the media
 element whose audio tracks are represented by the `AudioTrackList` object.
 This happens when tracks are added to the element when the media is first attached to
 the element; one `addtrack` event will occur for each audio track in the
 media resource.

This event is not cancelable and does not bubble.

### Use cases

You can use this event to react to a new audio track becoming available. You may want to update your UI elements to allow for user selection of the new audio track, for example.

Examples
--------

Using `addEventListener()`:


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

videoElement.audioTracks.addEventListener("addtrack", (event) => {
  console.log(`Audio track: ${event.track.label} added`);
});
```


Using the `onaddtrack` event handler property:


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

videoElement.audioTracks.onaddtrack = (event) => {
  console.log(`Audio track: ${event.track.label} added`);
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-addtrack |
| HTML Standard # handler-tracklist-onaddtrack |

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

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

See also
--------

* Related events: `removetrack`, `change`
* This event on `VideoTrackList` targets: `addtrack`
* This event on `MediaStream` targets: `addtrack`
* Media Capture and Streams API
* WebRTC
AudioTrackList: getTrackById() method
=====================================

 The **`AudioTrackList`** method
 **`getTrackById()`** returns the first
 `AudioTrack` object from the track list whose `id` matches the specified string. This lets you find a specified track if
 you know its ID string.

Syntax
------


```js
getTrackById(id)
```

### Parameters

`id`

 A string indicating the ID of the track to locate within the track
 list.


### Return value

 An `AudioTrack` object indicating the first track found within the
 `AudioTrackList` whose `id` matches the specified string. If no
 match is found, this method returns `null`.

 The tracks are searched in their natural order; that is, in the order defined by the
 media resource itself, or, if the resource doesn't define an order, the relative order
 in which the tracks are declared by the media resource.

Examples
--------

 This example suggests a hypothetical game in which movies are used as cut-scenes or
 other key set pieces within the game. Each movie has one audio track for each character,
 as well as one for the music, sound effects, and so forth. This function allows the game
 to disable a specific character's audio in order to adjust the movie's performance based
 on occurrences within the game; if the character's dialog isn't relevant, it gets left
 out. Obviously, that would require some clever graphic design to make work, but it's a
 hypothetical game.


```js
function disableCharacter(videoElem, characterName) {
  videoElem.audioTracks.getTrackById(characterName).enabled = false;
}
```


 This short function gets the `AudioTrackList` containing the video's audio
 tracks using `HTMLMediaElement.audioTracks`, then calls
 `getTrackById()` on it, specifying the character's name. The resulting
 track's audio is then disabled by setting its `enabled` flag to `false`.

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

| Specification |
| --- |
| HTML Standard # dom-audiotracklist-gettrackbyid-dev |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Response: headers property
==========================

 The **`headers`** read-only property of the
 `Response` interface contains the `Headers` object associated
 with the response.

Value
-----

A `Headers` object.

Examples
--------

 In our Fetch Response example (see Fetch Response live)
 we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`,
 create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block, we log the response headers to the console.


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

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.headers =", response.headers);
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-headers① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: text() method
=======================

 The **`text()`** method of the `Response` interface takes a `Response` stream and reads it to completion.
 It returns a promise that resolves with a `String`.
 The response is *always* decoded using UTF-8.

Syntax
------


```js
text()
```

### Parameters

None.

### Return value

A Promise that resolves with a `String`.

Examples
--------

 In our fetch text example (run fetch text live), we have an `<article>` element and three links (stored in the `myLinks` array.)
 First, we loop through all of these and give each one an `onclick` event handler so that the `getData()` function is run — with the link's `data-page` identifier passed to it as an argument — when one of the links is clicked.

 When `getData()` is run, we create a new request using the `Request()` constructor, then use it to fetch a specific `.txt` file.
 When the fetch is successful, we read a string out of the response using `text()`, then set the `innerText` of the `<article>` element equal to the text object.


```js
const myArticle = document.querySelector("article");
const myLinks = document.querySelectorAll("ul a");

for (const link of myLinks) {
  link.onclick = (e) => {
    e.preventDefault();
    const linkData = e.target.getAttribute("data-page");
    getData(linkData);
  };
}

function getData(pageId) {
  console.log(pageId);
  const myRequest = new Request(`${pageId}.txt`);
  fetch(myRequest)
    .then((response) => response.text())
    .then((text) => {
      myArticle.innertext = text;
    });
}
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-text① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: error() static method
===============================

The **`error()`** static method of the `Response` interface returns a new `Response` object associated with a network error.

This is mainly useful when writing service workers: it enables a service worker to send a response from a `fetch` event handler that will cause the `fetch()` call in the main app code to reject the promise.

An error response has its `type` set to `error`.

Syntax
------


```js
Response.error()
```

### Parameters

None.

### Return value

A `Response` object.

Examples
--------

### Returning a network error from a service worker

Suppose a web app has a service worker, which contains the following `fetch` event handler:


```js
// service-worker.js

self.addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);
  if (url.pathname === "/salamander.jpg") {
    event.respondWith(Response.error());
  }
});
```


With this service worker, all fetch requests from the app will pass through the service worker to the network, except for requests to fetch "salamander.jpg", which will reject. This means that the following main thread code would throw an error, and the `catch` handler will run.


```js
// main.js

const image = document.querySelector("#image");

try {
  const response = await fetch("salamander.jpg");
  const blob = await response.blob();
  const objectURL = URL.createObjectURL(blob);
  image.src = objectURL;
} catch (e) {
  console.error(e);
}
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-error① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: Response() constructor
================================

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

Syntax
------


```js
new Response()
new Response(body)
new Response(body, options)
```

### Parameters

`body` Optional

 An object defining a body for the response. This can be `null` (which is
 the default value), or one of:


* `Blob`
* `ArrayBuffer`
* `TypedArray`
* `DataView`
* `FormData`
* `ReadableStream`
* `URLSearchParams`
* `String`
* string literal

`options` Optional

An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are:

`status`

 The status code for the response.
 The default value is `200`.


`statusText`

 The status message associated with the status code, such as `"OK"`.
 The default value is `""`.


`headers`

 Any headers you want to add to your response, contained within a `Headers` object or object literal of `String` key/value pairs (see HTTP headers for a reference).
 By default this is empty.



Examples
--------

 In our Fetch Response example (see Fetch Response live)
 we create a new `Response` object using the constructor, passing it a new `Blob` as a body, and an init object containing a custom `status` and `statusText`:


```js
const myBlob = new Blob();
const myOptions = { status: 200, statusText: "SuperSmashingGreat!" };
const myResponse = new Response(myBlob, myOptions);
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: ok property
=====================

The **`ok`** read-only property of the `Response` interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.

Value
-----

A boolean value.

Examples
--------

 In our Fetch Response example (see Fetch Response live)
 we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

**Note:** at the top of the `fetch()` block we log the response `ok` value to the console.


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

const myRequest = new Request("flowers.jpg");

fetch(myRequest).then((response) => {
  console.log(response.ok); // returns true if the response returned successfully
  response.blob().then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
});
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-ok② |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: status property
=========================

The **`status`** read-only property of the `Response` interface contains the HTTP status codes of the response.

For example, `200` for success, `404` if the resource could not be found.

Value
-----

 An unsigned short number.
 This is one of the HTTP response status codes.

Examples
--------

 In our Fetch Response example (see Fetch Response live)
 we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block we log the response `status` value to the console.


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

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.status =", response.status); // response.status = 200
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-status① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: statusText property
=============================

The **`statusText`** read-only property of the `Response` interface contains the status message corresponding to the HTTP status code in `Response.status`.

For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`.

Value
-----

 A `String` containing the HTTP status message associated with the response.
 The default value is "".

 See HTTP response status codes for a list of codes and their associated status messages.
 Note that HTTP/2 does not support status messages.

Examples
--------

 In our Fetch Response example (see Fetch Response live) we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block we log the response `statusText` value to the console.


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

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.statusText =", response.statusText); // response.statusText = "OK"
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-statustext① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: arrayBuffer() method
==============================

 The **`arrayBuffer()`** method of the `Response` interface
 takes a `Response` stream and reads it to completion. It returns a promise
 that resolves with an `ArrayBuffer`.

Syntax
------


```js
arrayBuffer()
```

### Parameters

None.

### Return value

A promise that resolves with an `ArrayBuffer`.

Examples
--------

### Playing music

 In our fetch array buffer live, we have a Play button. When pressed, the `getData()`
 function is run. Note that before playing full audio file will be downloaded. If you
 need to play ogg during downloading (stream it) - consider
 `HTMLAudioElement`:


```js
new Audio("music.ogg").play();
```


 In `getData()` we create a new request using the
 `Request()` constructor, then use it to fetch an OGG
 music track. We also use `AudioContext.createBufferSource` to create an
 audio buffer source. When the fetch is successful, we read an `ArrayBuffer`
 out of the response using `arrayBuffer()`, decode the audio data using
 `AudioContext.decodeAudioData()`, set the decoded data as the audio buffer
 source's buffer (`source.buffer`), then connect the source up to the
 `AudioContext.destination`.

 Once `getData()` has finished running, we start the audio source playing
 with `start(0)`, then disable the play button so it can't be clicked again
 when it is already playing (this would cause an error.)


```js
function getData() {
  const audioCtx = new AudioContext();

  return fetch("viper.ogg")
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error, status = ${response.status}`);
      }
      return response.arrayBuffer();
    })
    .then((buffer) => audioCtx.decodeAudioData(buffer))
    .then((decodedData) => {
      const source = new AudioBufferSourceNode();
      source.buffer = decodedData;
      source.connect(audioCtx.destination);
      return source;
    });
}

// wire up buttons to stop and play audio

play.onclick = () => {
  getData().then((source) => {
    source.start(0);
    play.setAttribute("disabled", "disabled");
  });
};
```

### Reading files

 The `Response()` constructor accepts
 `File`s and `Blob`s, so it may be used to read a
 `File` into other formats.


```js
function readFile(file) {
  return new Response(file).arrayBuffer();
}
```



```html
<input type="file" onchange="readFile(this.files[0])" />
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-arraybuffer① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP