Background Fetch API - Web APIs

Background Fetch API
====================

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

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

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **Background Fetch API** provides a method for managing downloads that may take a significant amount of time such as movies, audio files, and software.

Concepts and Usage
------------------

When a web application requires the user to download large files, this often presents a problem in that the user needs to stay connected to the page for the download to complete. If they lose connectivity, close the tab or navigate away from the page the download stops.

The Background Synchronization API provides a way for service workers to defer processing until a user is connected; however it can't be used for long running tasks such as downloading a large file. Background Sync requires that the service worker stays alive until the fetch is completed, and to conserve battery life and to prevent unwanted tasks happening in the background the browser will at some point terminate the task.

The Background Fetch API solves this problem. It creates a way for a web developer to tell the browser to perform some fetches in the background, for example when the user clicks a button to download a video file. The browser then performs the fetches in a user-visible way, displaying progress to the user and giving them a method to cancel the download. Once the download is complete the browser then opens the service worker, at which point your application can do something with the response if required.

The Background Fetch API will enable the fetch to happen if the user starts the process while offline. Once they are connected it will begin. If the user goes off line, the process pauses until the user is on again.

Interfaces
----------

`BackgroundFetchManager`
Experimental

A map where the keys are background fetch IDs and the values are `BackgroundFetchRegistration` objects.

`BackgroundFetchRegistration`
Experimental

Represents a Background Fetch.

`BackgroundFetchRecord`
Experimental

Represents an individual fetch request and response.

`BackgroundFetchEvent`
Experimental

The event type for the `backgroundfetchabort` and `backgroundfetchclick` event

`BackgroundFetchUpdateUIEvent`
Experimental

The event type for the `backgroundfetchsuccess` and `backgroundfetchfail` event

### Extensions to other interfaces

`ServiceWorkerRegistration.backgroundFetch` Read only
Experimental

Returns a reference to a `BackgroundFetchManager` object, which manages background fetch operations.

`backgroundfetchabort` event
Experimental

Fired when a background fetch operation has been canceled by the user or the app.

`backgroundfetchclick` event
Experimental

Fired when the user has clicked on the UI for a background fetch operation.

`backgroundfetchfail` event
Experimental

Fired when at least one of the requests in a background fetch operation has failed.

`backgroundfetchsuccess` event
Experimental

Fired when all of the requests in a background fetch operation have succeeded.

Examples
--------

Before using Background Fetch, check for browser support.

```js
if (!("BackgroundFetchManager" in self)) {
  // Provide fallback downloading.
}
```

 Using Background Fetch requires a registered service worker. Then call `backgroundFetch.fetch()` to perform a fetch. This
 returns a promise that resolves with a `BackgroundFetchRegistration`.

A background fetch may fetch a number of files. In our example the fetch requests an MP3 and a JPEG. This enables a package of files that the user sees as one item (for example a podcast and artwork) to be downloaded at once.

```js
navigator.serviceWorker.ready.then(async (swReg) => {
  const bgFetch = await swReg.backgroundFetch.fetch(
    "my-fetch",
    ["/ep-5.mp3", "ep-5-artwork.jpg"],
    {
      title: "Episode 5: Interesting things.",
      icons: [
        {
          sizes: "300x300",
          src: "/ep-5-icon.png",
          type: "image/png",
        },
      ],
      downloadTotal: 60 \* 1024 \* 1024,
    },
  );
});
```

You can find a demo application which implements Background Fetch here.

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

| Specification |
| --- |
| Background Fetch  |

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

### api.BackgroundFetchManager

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

### api.BackgroundFetchRegistration

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

### api.BackgroundFetchRecord

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

See also
--------

* Introducing Background Fetch
* Background Fetch - HTTP 203


FileSystemFileHandle - Web APIs

FileSystemFileHandle
====================

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

The **`FileSystemFileHandle`** interface of the File System API represents a handle to a file system entry. The interface is accessed through the `window.showOpenFilePicker()` method.

Note that read and write operations depend on file-access permissions that do not persist after a page refresh if no other tabs for that origin remain open. The `queryPermission` method of the `FileSystemHandle` interface can be used to verify permission state before accessing a file.

FileSystemHandle

FileSystemFileHandleInstance properties
-------------------

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

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

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

`getFile()`

 Returns a `Promise` which resolves to a `File` object
 representing the state on disk of the entry represented by the handle.

`createSyncAccessHandle()`

 Returns a `Promise` which resolves to a `FileSystemSyncAccessHandle` object
 that can be used to synchronously read from and write to a file. The synchronous nature of this method brings performance advantages,
 but it is only usable inside dedicated Web Workers.

`createWritable()`

 Returns a `Promise` which resolves to a newly created `FileSystemWritableFileStream`
 object that can be used to write to a file.

Examples
--------

### Reading a File

The following asynchronous function presents a file picker and once a file is chosen, uses the `getFile()` method to retrieve the contents.

```js
async function getTheFile() {
  const pickerOpts = {
    types: [
      {
        description: "Images",
        accept: {
          "image/\*": [".png", ".gif", ".jpeg", ".jpg"],
        },
      },
    ],
    excludeAcceptAllOption: true,
    multiple: false,
  };

  // open file picker
  const [fileHandle] = await window.showOpenFilePicker(pickerOpts);
  // get file contents
  const fileData = await fileHandle.getFile();
  return fileData;
}
```

### Writing a File

The following asynchronous function writes the given contents to the file handle, and thus to disk.

```js
async function writeFile(fileHandle, contents) {
  // Create a FileSystemWritableFileStream to write to.
  const writable = await fileHandle.createWritable();

  // Write the contents of the file to the stream.
  await writable.write(contents);

  // Close the file and write the contents to disk.
  await writable.close();
}
```

### Synchronously reading and writing a file

The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:

* Creates a synchronous file access handle.
* Gets the size of the file and creates an `ArrayBuffer` to contain it.
* Reads the file contents into the buffer.
* Encodes the message and writes it to the end of the file.
* Persists the changes to disk and closes the access handle.

```js
onmessage = async (e) => {
  // Retrieve message sent to work from main script
  const message = e.data;

  // Get handle to draft file
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Get size of the file.
  const fileSize = accessHandle.getSize();
  // Read file content to a buffer.
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // Write the message to the end of the file.
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
};
```

**Note:** In earlier versions of the spec, `close()`, `flush()`, `getSize()`, and `truncate()` were wrongly specified as asynchronous methods, and older versions of some browsers implement them in this way. However, all current browsers that support these methods implement them as synchronous methods.

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

| Specification |
| --- |
| File System Standard # api-filesystemfilehandle |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


MediaEncryptedEvent: MediaEncryptedEvent() constructor - Web APIs

MediaEncryptedEvent: MediaEncryptedEvent() constructor
======================================================

The **`MediaEncryptedEvent`** constructor creates a new `MediaEncryptedEvent` object.

**Note:** In normal cases, you don't need to call this constructor in your code as such events are usually generated by the browser when needed.

Syntax
------

```js
new MediaEncryptedEvent(type)
new MediaEncryptedEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `encrypted`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`initDataType`

A string with the type of the initialization data contained in this object

`message`

An `ArrayBuffer` with the initialization data, or `null` if there is none.

### Return value

A new `MediaEncryptedEvent` object.

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

| Specification |
| --- |
| Encrypted Media Extensions # dom-mediaencryptedevent |

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

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


MediaEncryptedEvent: initData property - Web APIs

MediaEncryptedEvent: initData property
======================================

The read-only **`initData`** property of the `MediaKeyMessageEvent` returns the initialization data contained in this event, if any.

Value
-----

A `ArrayBuffer` with the initialization data, or `null` if there are none.

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

| Specification |
| --- |
| Encrypted Media Extensions # dom-mediaencryptedevent-initdata |

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

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


MediaEncryptedEvent: initDataType property - Web APIs

MediaEncryptedEvent: initDataType property
==========================================

The read-only **`initDataType`** property of the `MediaKeyMessageEvent` returns a case-sensitive string describing the type of the initialization data associated with this event.

Value
-----

A string.

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

| Specification |
| --- |
| Encrypted Media Extensions # dom-mediaencryptedevent-initdatatype |

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

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


ViewTransition: skipTransition() method - Web APIs

ViewTransition: skipTransition() method
=======================================

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

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

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`skipTransition()`** method of the
 `ViewTransition` interface skips the animation part of the view transition, but doesn't skip running the `document.startViewTransition()` callback that updates the DOM.

Syntax
------

```js
skipTransition()
```

### Parameters

None.

### Return value

`undefined`.

Examples
--------

```js
// start new view transition
const transition = document.startViewTransition(() => displayNewImage());

// skip the animation and just update the DOM
transition.skipTransition();
```

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

| Specification |
| --- |
| CSS View Transitions Module Level 1 # dom-viewtransition-skiptransition |

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

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

See also
--------

* Smooth and simple transitions with the View Transitions API


ViewTransition: ready property - Web APIs

ViewTransition: ready property
==============================

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

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

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`ready`** read-only property of the
 `ViewTransition` interface is a `Promise` that fulfills once the pseudo-element tree is created and the transition animation is about to start.

`ready` will reject if the transition cannot begin. This can be due to misconfiguration, for example duplicate `view-transition-name`s, or if the callback passed to `Document.startViewTransition()` throws or returns a promise that rejects.

Value
-----

A promise.

Examples
--------

In the following example, `ready` is used to trigger a custom circular reveal view transition emanating from the position of the user's cursor on click, with animation provided by the Web Animations API.

```js
// Store the last click event
let lastClick;
addEventListener("click", (event) => (lastClick = event));

function spaNavigate(data) {
  // Fallback for browsers that don’t support this API:
  if (!document.startViewTransition) {
    updateTheDOMSomehow(data);
    return;
  }

  // Get the click position, or fallback to the middle of the screen
  const x = lastClick?.clientX ?? innerWidth / 2;
  const y = lastClick?.clientY ?? innerHeight / 2;
  // Get the distance to the furthest corner
  const endRadius = Math.hypot(
    Math.max(x, innerWidth - x),
    Math.max(y, innerHeight - y),
  );

  // Create a transition:
  const transition = document.startViewTransition(() => {
    updateTheDOMSomehow(data);
  });

  // Wait for the pseudo-elements to be created:
  transition.ready.then(() => {
    // Animate the root’s new view
    document.documentElement.animate(
      {
        clipPath: [
          `circle(0 at ${x}px ${y}px)`,
          `circle(${endRadius}px at ${x}px ${y}px)`,
        ],
      },
      {
        duration: 500,
        easing: "ease-in",
        // Specify which pseudo-element to animate
        pseudoElement: "::view-transition-new(root)",
      },
    );
  });
}
```

This animation also requires the following CSS, to turn off the default CSS animation and stop the old and new view states from blending in any way (the new state "wipes" right over the top of the old state, rather than transitioning in):

```css
::view-transition-image-pair(root) {
  isolation: auto;
}

::view-transition-old(root),
::view-transition-new(root) {
  animation: none;
  mix-blend-mode: normal;
  display: block;
}
```

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

| Specification |
| --- |
| CSS View Transitions Module Level 1 # dom-viewtransition-ready |

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

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

See also
--------

* Smooth and simple transitions with the View Transitions API


ViewTransition: finished property - Web APIs

ViewTransition: finished property
=================================

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

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

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`finished`** read-only property of the
 `ViewTransition` interface is a `Promise` that fulfills once the transition animation is finished, and the new page view is visible and interactive to the user.

`finished` only rejects if the callback passed to `document.startViewTransition()`throws or returns a promise that rejects, which indicates that the new state of the page wasn't created.

If a transition animation fails to start, or is skipped during the animation using `ViewTransition.skipTransition()`, the end state is still reached therefore `finished` still fulfills.

Value
-----

A promise.

Examples
--------

### Different transitions for different navigations

Sometimes certain navigations will require specifically tailored transitions, for example a 'back' navigation may want a different transition to a 'forward' navigation. The best way to handle such cases is to set a class name on the `<html>` element, handle the transition — applying the correct animation using a tailored selector — and then remove the class name once the transition is finished.

```js
async function handleTransition() {
  if (isBackNavigation) {
    document.documentElement.classList.add("back-transition");
  }

  const transition = document.startViewTransition(() =>
    updateTheDOMSomehow(data),
  );

  try {
    await transition.finished;
  } finally {
    document.documentElement.classList.remove("back-transition");
  }
}
```

**Note:** `isBackNavigation` isn't a built-in feature; it's a theoretical function that could perhaps be implemented using the Navigation API or similar.

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

| Specification |
| --- |
| CSS View Transitions Module Level 1 # dom-viewtransition-finished |

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

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

See also
--------

* Smooth and simple transitions with the View Transitions API


ViewTransition: updateCallbackDone property - Web APIs

ViewTransition: updateCallbackDone property
===========================================

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

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

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`updateCallbackDone`** read-only property of the
 `ViewTransition` interface is a `Promise` that fulfills when the promise returned by the `document.startViewTransition()`'s callback fulfills, or rejects when it rejects.

`updateCallbackDone` is useful when you don't care about the success/failure of the transition animation, and just want to know if and when the DOM is updated.

Value
-----

A promise.

Examples
--------

```js
// start new view transition
const transition = document.startViewTransition(() => displayNewImage());

transition.updateCallbackDone.then(() => {
  // Respond to the DOM being updated successfully
});
```

See Transitions as an enhancement for a useful example.

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

| Specification |
| --- |
| CSS View Transitions Module Level 1 # dom-viewtransition-updatecallbackdone |

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

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

See also
--------

* Smooth and simple transitions with the View Transitions API


Navigation: navigateerror event - Web APIs

Navigation: navigateerror event
===============================

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

The **`navigateerror`** event of the `Navigation` interface is fired when a navigation fails.

For example, if the network is down, any `fetch()` method invoked to handle a navigation will fail, and the error will be routed to `navigateerror`.

Syntax
------

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

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

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

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

An `ErrorEvent`. Inherits from `Event`.

Event

ErrorEventExamples
--------

You might deal with a successful navigation by hiding a previously displayed progress indicator, like this:

```js
navigation.addEventListener("navigatesuccess", (event) => {
  loadingIndicator.hidden = true;
});
```

Or you might show an error message on failure:

```js
navigation.addEventListener("navigateerror", (event) => {
  loadingIndicator.hidden = true; // also hide indicator
  showMessage(`Failed to load page: ${event.message}`);
});
```

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

| Specification |
| --- |
| HTML Standard # event-navigateerror |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: currententrychange event - Web APIs

Navigation: currententrychange event
====================================

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

The **`currententrychange`** event of the `Navigation` interface is fired when the `Navigation.currentEntry` has changed.

This event will fire for:

* Same-document navigations (e.g. `back()` or `traverseTo()`).
* Replacements (i.e. a `navigate()` call with `history` set to `replace`).
* Other calls that change the entry's state (e.g. `updateCurrentEntry()`, or the History API's `History.replaceState()`).

This event fires after the navigation is committed, meaning that the visible URL has changed and the `NavigationHistoryEntry` update has occurred. It is useful for migrating from usage of older API features like the `hashchange` or `popstate` events.

Syntax
------

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

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

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

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

A `NavigationCurrentEntryChangeEvent`. Inherits from `Event`.

Event

NavigationCurrentEntryChangeEventExamples
--------

Navigation data reporting:

```js
navigation.addEventListener("currententrychange", () => {
  const data = navigation.currentEntry.getState();
  submitAnalyticsData(data.analytics);
});
```

Setting up a per-entry event:

```js
navigation.addEventListener("currententrychange", () => {
  navigation.currentEntry.addEventListener("dispose", genericDisposeHandler);
});
```

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

| Specification |
| --- |
| HTML Standard # event-currententrychange |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: canGoForward property - Web APIs

Navigation: canGoForward property
=================================

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

 The **`canGoForward`** read-only property of the
 `Navigation` interface returns `true` if it is possible to navigate forwards in the navigation history
 (i.e. the `currentEntry` is not the last one in the history entry list),
 and `false` if it is not.

Value
-----

A boolean value: `true` if it is possible to navigate forwards in the navigation history, `false` otherwise.

Examples
--------

```js
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-cangoforward-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: navigatesuccess event - Web APIs

Navigation: navigatesuccess event
=================================

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

The **`navigatesuccess`** event of the `Navigation` interface is fired when a successful navigation has finished.

In the case of an intercepted navigation, this would occur after any promises returned by your `intercept()` handler are fulfilled. The `NavigationTransition.finished` promise will also fulfill at the same time.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

You might deal with a successful navigation by hiding a previously displayed progress indicator, like this:

```js
navigation.addEventListener("navigatesuccess", (event) => {
  loadingIndicator.hidden = true;
});
```

Or you might show an error message on failure:

```js
navigation.addEventListener("navigateerror", (event) => {
  loadingIndicator.hidden = true; // also hide indicator
  showMessage(`Failed to load page: ${event.message}`);
});
```

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

| Specification |
| --- |
| HTML Standard # event-navigatesuccess |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: entries() method - Web APIs

Navigation: entries() method
============================

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

 The **`entries()`** method of the
 `Navigation` interface returns an array of `NavigationHistoryEntry` objects representing all existing history entries.

Syntax
------

```js
entries()
```

### Parameters

None.

### Return value

An array of `NavigationHistoryEntry` objects.

### Exceptions

None.

Examples
--------

### Return the number of entries in the history

```js
let numOfEntries = navigation.entries().length - 1;
```

### A smart back button

A page-supplied "back" button can take you back, even after reload, by inspecting the previous history entries:

```js
backButtonEl.addEventListener("click", () => {
  if (
    navigation.entries()[navigation.currentEntry.index - 1]?.url ===
    "/product-listing"
  ) {
    navigation.back();
  } else {
    // If the user arrived here in some other way
    // e.g. by typing the URL directly:
    navigation.navigate("/product-listing", { history: "replace" });
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-entries-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: reload() method - Web APIs

Navigation: reload() method
===========================

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

 The **`reload()`** method of the
 `Navigation` interface reloads the current URL, updating any provided state in the history entries list.

Syntax
------

```js
navigate(options)
```

### Parameters

`options` Optional

An options object containing the following properties:

`state` Optional

Developer-defined information to be stored in the associated `NavigationHistoryEntry` once the navigation is complete, retrievable via `getState()`. This can be any data type. You might, for example, wish to store a page visit count for analytics purposes, or store UI state details so the view can be shown exactly as the user last left it. Any data stored in `state` must be structured-cloneable.

`info` Optional

Developer-defined information to be passed along to the `navigate` event, made available in `NavigateEvent.info`. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`.

### Return value

An object with the following properties:

`committed`

A `Promise` which will fulfill when the visible URL has changed and a new `NavigationHistoryEntry` has been created.

`finished`

A `Promise` which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires.

Either one of these promises rejects if the navigation has failed for some reason.

### Exceptions

`DataCloneError` `DOMException`

Thrown if the `state` parameter had values included in it that are not structured-cloneable.

Examples
--------

### Using info and state

```js
async function handleReload() {
  await navigation.reload({
    info: { animation: "fade-in" },
    state: { infoPaneOpen: true },
  }).finished;

  // Update application state
  // ...
}
```

Reload page and add a new state item:

```js
async function handleReload() {
  await navigation.reload({
    state: { ...navigation.currentEntry.getState(), newState: 3 },
  }).finished;

  // Update application state
  // ...
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-reload-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: currentEntry property - Web APIs

Navigation: currentEntry property
=================================

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

 The **`currentEntry`** read-only property of the
 `Navigation` interface returns a `NavigationHistoryEntry` object representing the location the user is currently navigated to right now.

Value
-----

A `NavigationHistoryEntry` object.

Examples
--------

```js
function initHomeBtn() {
  // Get the key of the first loaded entry
  // so the user can always go back to this view.
  const { key } = navigation.currentEntry;
  backToHomeButton.onclick = () => {
    navigation.traverseTo(key);
  };
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
  event.intercept({
    async handler() {
      // Navigate to a different view,
      // but the "home" button will always work.
    },
  });
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-currententry-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: transition property - Web APIs

Navigation: transition property
===============================

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

The **`transition`** read-only property of the `Navigation` interface returns a `NavigationTransition` object representing the status of an in-progress navigation, which can be used to track it.

Value
-----

A `NavigationTransition` object, or `null` if no navigation is currently in progress.

Examples
--------

```js
async function handleTransition() {
  if (navigation.transition) {
    showLoadingSpinner();
    await navigation.transition.finished;
    hideLoadingSpinner();
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-transition-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: forward() method - Web APIs

Navigation: forward() method
============================

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

 The **`forward()`** method of the
 `Navigation` interface navigates forwards by one entry in the navigation history.

Syntax
------

```js
forward(options)
```

### Parameters

`options` Optional

An options object containing the following properties:

`info` Optional

Developer-defined information to be passed along to the `navigate` event, made available in `NavigateEvent.info`. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`.

### Return value

An object with the following properties:

`committed`

A `Promise` which will fulfill when the visible URL has changed and a new `NavigationHistoryEntry` has been created.

`finished`

A `Promise` which will fulfill when all promises returned by the `NavigateEvent.intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires.

Either one of these promises rejects if the navigation has failed for some reason.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `Navigation.currentEntry`'s `NavigationHistoryEntry.index` value is -1 or `navigation.entries().length - 1`, i.e. either the current `Document` is not yet active, or the current history entry is the last one in the history, meaning that forwards navigation is not possible, or if the current `Document` is unloading.

Examples
--------

```js
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-forward-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: back() method - Web APIs

Navigation: back() method
=========================

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

 The **`back()`** method of the
 `Navigation` interface navigates backwards by one entry in the navigation history.

Syntax
------

```js
back(options)
```

### Parameters

`options` Optional

An options object containing the following properties:

`info` Optional

Developer-defined information to be passed along to the `navigate` event, made available in `NavigateEvent.info`. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`.

### Return value

An object with the following properties:

`committed`

A `Promise` which will fulfill when the visible URL has changed and a new `NavigationHistoryEntry` has been created.

`finished`

A `Promise` which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires.

Either one of these promises rejects if the navigation has failed for some reason.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `Navigation.currentEntry`'s `NavigationHistoryEntry.index` value is -1 or 0, i.e. either the current `Document` is not yet active, or the current history entry is the first one in the history, meaning that backwards navigation is not possible, or if the current `Document` is unloading.

Examples
--------

```js
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-back-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: updateCurrentEntry() method - Web APIs

Navigation: updateCurrentEntry() method
=======================================

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

The **`updateCurrentEntry()`** method of the `Navigation` interface updates the `state` of the `currentEntry`; used in cases where the state change will be independent of a navigation or reload.

Syntax
------

```js
updateCurrentEntry()
updateCurrentEntry(options)
```

### Parameters

`options` Optional

An options object containing the following properties:

`state`

Developer-defined information to be stored in the associated `NavigationHistoryEntry` once the navigation is complete, retrievable via `getState()`. This can be any data type. You might, for example, wish to store a page visit count for analytics purposes, or store UI state details so the view can be shown exactly as the user last left it. Any data stored in `state` must be structured-cloneable.

### Return value

None (`undefined`).

### Exceptions

`DataCloneError` `DOMException`

Thrown if the `state` parameter had values included in it that are not structured-cloneable.

`InvalidStateError` `DOMException`

Thrown if the `Navigation.currentEntry` is `null`, i.e. there is no current history entry. This could occur for example if the current page is `about:blank`.

Examples
--------

You could use something like the following to update the open/closed state of a `<details>` element so that the state can be restored when reloading the page or navigating back from somewhere else.

```js
detailsElem.addEventListener("toggle", () => {
  navigation.updateCurrentEntry({ state: { detailOpen: detailsElem.open } });
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-updatecurrententry-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: navigate event - Web APIs

Navigation: navigate event
==========================

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

The **`navigate`** event of the `Navigation` interface is fired when any type of navigation is initiated, allowing you to intercept as required.

Syntax
------

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

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

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

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

A `NavigateEvent`. Inherits from `Event`.

Event

NavigateEventExamples
--------

### Handling a navigation using `intercept()`

```js
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) {
    return;
  }

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        // The URL has already changed, so show a placeholder while
        // fetching the new content, such as a spinner or loading page
        renderArticlePagePlaceholder();

        // Fetch the new content and display when ready
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);
      },
    });
  }
});
```

**Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `event.preventDefault()`, perform the appropriate `History.pushState()` call, then set up the page view based on the new URL. And this wouldn't handle all navigations — only user-initiated link clicks.

### Handling scrolling using `scroll()`

In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a `scroll()` call between the two.

```js
navigation.addEventListener("navigate", (event) => {
  if (shouldNotIntercept(navigateEvent)) {
    return;
  }
  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);

        event.scroll();

        const secondaryContent = await getSecondaryContent(url.pathname);
        addSecondaryContent(secondaryContent);
      },
    });
  }
});
```

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

| Specification |
| --- |
| HTML Standard # event-navigate |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: navigate() method - Web APIs

Navigation: navigate() method
=============================

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

 The **`navigate()`** method of the
 `Navigation` interface navigates to a specific URL, updating any provided state in the history entries list.

Syntax
------

```js
navigate(url)
navigate(url, options)
```

### Parameters

`url`

The destination URL to navigate to. Note that when calling `navigate()` on a another window's `navigation` object, the URL will be resolved relative to the target window's URL, not the calling window's URL. This matches the behavior of the History API, but not the behavior of the Location API.

`options` Optional

An options object containing the following properties:

`state` Optional

Developer-defined information to be stored in the associated `NavigationHistoryEntry` once the navigation is complete, retrievable via `getState()`. This can be any data type. You might, for example, wish to store a page visit count for analytics purposes, or store UI state details so the view can be shown exactly as the user last left it. Any data stored in `state` must be structured-cloneable.

`info` Optional

Developer-defined information to be passed along to the `navigate` event, made available in `NavigateEvent.info`. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`.

`history` Optional

An enumerated value that sets the history behavior of this navigation. The available values are:

* `auto`: The default value; will usually perform a `push` navigation but will perform a `replace` navigation under special circumstances (see the `NotSupportedError` description below).
* `push`: Will push a new `NavigationHistoryEntry` onto the entries list, or fail under special circumstances (see the `NotSupportedError` description below).
* `replace`: Will replace the current `NavigationHistoryEntry`.

### Return value

An object with the following properties:

`committed`

A `Promise` which will fulfill when the visible URL has changed and a new `NavigationHistoryEntry` has been created.

`finished`

A `Promise` which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires.

Either one of these promises rejects if the navigation has failed for some reason.

### Exceptions

`DataCloneError` `DOMException`

Thrown if the `state` parameter had values included in it that are not structured-cloneable.

`SyntaxError` `DOMException`

Thrown if the `url` parameter is not a valid URL.

`NotSupportedError` `DOMException`

Thrown if the `history` option is set to `push`, and any of the following special circumstances are true:

* The browser is currently showing the initial `about:blank` document.
* The `url`'s scheme is `javascript`.

Examples
--------

### Set up home button

```js
function initHomeBtn() {
  // Get the key of the first loaded entry
  // so the user can always go back to this view.
  const { key } = navigation.currentEntry;
  backToHomeButton.onclick = () => {
    navigation.traverseTo(key);
  };
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
  event.intercept({
    async handler() {
      // Navigate to a different view,
      // but the "home" button will always work.
    },
  });
});
```

### A smart back button

A page-supplied "back" button can take you back, even after reload, by inspecting the previous history entries:

```js
backButtonEl.addEventListener("click", () => {
  if (
    navigation.entries()[navigation.currentEntry.index - 1]?.url ===
    "/product-listing"
  ) {
    navigation.back();
  } else {
    // If the user arrived here in some other way
    // e.g. by typing the URL directly:
    navigation.navigate("/product-listing", { history: "replace" });
  }
});
```

### Using info and state

```js
async function navigateHandler() {
  await navigation.navigate(url, {
    info: { animation: "swipe-right" },
    state: { infoPaneOpen: true },
  }).finished;

  // Update application state
  // ...
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-navigate-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: canGoBack property - Web APIs

Navigation: canGoBack property
==============================

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

 The **`canGoBack`** read-only property of the
 `Navigation` interface returns `true`
 if it is possible to navigate backwards in the navigation history
 (i.e. the `currentEntry` is
 not the first one in the history entry list),
 and `false` if it is not.

Value
-----

A boolean value: `true` if it is possible to navigate backwards in the navigation history, `false` otherwise.

Examples
--------

```js
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-cangoback-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Navigation: traverseTo() method - Web APIs

Navigation: traverseTo() method
===============================

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

The **`traverseTo()`** method of the `Navigation` interface navigates to the `NavigationHistoryEntry` identified by the given `key`.

Syntax
------

```js
traverseTo(key)
traverseTo(key, options)
```

### Parameters

`key`

The `key` of the `NavigationHistoryEntry` to navigate to.

`options` Optional

An options object containing the following properties:

`info` Optional

Developer-defined information to be passed along to the `navigate` event, made available in `NavigateEvent.info`. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`.

### Return value

An object with the following properties:

`committed`

A `Promise` which will fulfill when the visible URL has changed and a new `NavigationHistoryEntry` has been created.

`finished`

A `Promise` which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires.

Either one of these promises rejects if the navigation has failed for some reason.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `Navigation.currentEntry`'s `NavigationHistoryEntry.index` value is -1, meaning the current `Document` is not yet active, of if the navigation history list does not contain a `NavigationHistoryEntry` with the specified key, or if the current `Document` is unloading.

Examples
--------

### Set up home button

```js
function initHomeBtn() {
  // Get the key of the first loaded entry
  // so the user can always go back to this view.
  const { key } = navigation.currentEntry;
  backToHomeButton.onclick = () => {
    navigation.traverseTo(key);
  };
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
  event.intercept({
    async handler() {
      // Navigate to a different view,
      // but the "home" button will always work.
    },
  });
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation-traverseto-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Location: pathname property - Web APIs

Location: pathname property
===========================

 The **`pathname`** property of the `Location`
 interface is a string containing the path of the URL for the location. If there is no path, `pathname` will be empty: otherwise, `pathname` contains an initial '/' followed by the path of the URL, not including the query string or fragment.

Value
-----

A string.

Examples
--------

```js
// Let's say we are on the URL https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname#examples
console.log(location.pathname); // '/en-US/docs/Web/API/Location/pathname'
```

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

| Specification |
| --- |
| HTML Standard # dom-location-pathname-dev |

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

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


Location: host property - Web APIs

Location: host property
=======================

 The **`host`** property of the `Location`
 interface is a string containing the host, that is the
 *hostname*, and then, if the *port* of the URL is nonempty, a
 `':'`, and the *port* of the URL.

Value
-----

A string.

Examples
--------

```js
const anchor = document.createElement("a");

anchor.href = "https://developer.mozilla.org/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org");

anchor.href = "https://developer.mozilla.org:443/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org");
// The port number is not included because 443 is the scheme's default port

anchor.href = "https://developer.mozilla.org:4097/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org:4097");
```

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

| Specification |
| --- |
| HTML Standard # dom-location-host-dev |

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

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


Location: port property - Web APIs

Location: port property
=======================

 The **`port`** property of the `Location`
 interface is a string containing the port number of the URL. If the
 URL does not contain an explicit port number, it will be set to `''`.

Value
-----

A string.

Examples
--------

```js
// Let's an <a id="myAnchor" href="https://developer.mozilla.org:443/en-US/docs/Location.port"> element be in the document
const anchor = document.getElementByID("myAnchor");
const result = anchor.port; // Returns:'443'
```

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

| Specification |
| --- |
| HTML Standard # dom-location-port-dev |

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

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


Location: search property - Web APIs

Location: search property
=========================

 The **`search`** property of the `Location`
 interface is a search string, also called a *query string*; that is, a
 string containing a `'?'` followed by the parameters of the
 URL.

 Modern browsers provide
 `URLSearchParams`
 and
 `URL.searchParams`
 to make it easy to parse out the parameters from the querystring.

Value
-----

A string.

Examples
--------

```js
// Let an <a id="myAnchor" href="/en-US/docs/Location.search?q=123"> element be in the document
const anchor = document.getElementById("myAnchor");
const queryString = anchor.search; // Returns:'?q=123'

// Further parsing:
const params = new URLSearchParams(queryString);
const q = parseInt(params.get("q")); // is the number 123
```

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

| Specification |
| --- |
| HTML Standard # dom-location-search-dev |

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

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


Location: toString() method - Web APIs

Location: toString() method
===========================

 The **`toString()`** stringifier method of the
 `Location` interface returns a string containing the
 whole URL. It is a read-only version of `Location.href`.

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the object's URL.

Examples
--------

```js
// Let's imagine this code is executed on https://example.com/path?search#hash
const result = window.location.toString(); // Returns: 'https://example.com/path?search#hash'
```

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

| Specification |
| --- |
| HTML Standard # dom-location-href-dev |

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

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


Location: protocol property - Web APIs

Location: protocol property
===========================

 The **`protocol`** property of the `Location`
 interface is a string representing the protocol scheme of the URL,
 including the final `':'`.

Value
-----

A string.

Examples
--------

```js
// Let's an <a id="myAnchor" href="https://developer.mozilla.org/en-US/Location.protocol"> element be in the document
const anchor = document.getElementById("myAnchor");
const result = anchor.protocol; // Returns:'https:'
```

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

| Specification |
| --- |
| HTML Standard # dom-location-protocol-dev |

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

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


Location: ancestorOrigins property - Web APIs

Location: ancestorOrigins property
==================================

 The **`ancestorOrigins`** read-only
 property of the `Location` interface is a static
 `DOMStringList` containing, in reverse order, the origins of all ancestor
 browsing contexts of the document associated with the given `Location`
 object.

 You can use `location.ancestorOrigins` in the script for a document to
 determine, for example, whenever the document is being framed by a site which you don't
 expect it to be framed by. You can also use it to vary the behavior of the document
 based on what site or list of sites is framing it.

Value
-----

A `DOMStringList`.

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

| Specification |
| --- |
| HTML Standard # dom-location-ancestororigins-dev |

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

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


Location: href property - Web APIs

Location: href property
=======================

 The **`href`** property of the `Location`
 interface is a stringifier that returns a string containing the whole
 URL, and allows the href to be updated.

 Setting the value of `href` *navigates* to the provided URL. If you
 want *redirection*, use `location.replace()`. The difference from setting the `href` property value is that when using the `location.replace()` method, after navigating to the given URL, the current page will not be saved in session history — meaning the user won't be able to use the back button to navigate to it.

Value
-----

A string.

Examples
--------

```js
// Lets imagine an <a id="myAnchor" href="https://developer.mozilla.org/en-US/Location/href"> element is in the document
const anchor = document.getElementById("myAnchor");
const result = anchor.href; // Returns: 'https://developer.mozilla.org/en-US/Location/href'
```

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

| Specification |
| --- |
| HTML Standard # dom-location-href-dev |

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

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


Location: hostname property - Web APIs

Location: hostname property
===========================

 The **`hostname`** property of the `Location`
 interface is a string containing the domain of the URL.

Value
-----

A string.

Examples
--------

```js
const anchor = document.createElement("a");
anchor.href = "https://developer.mozilla.org:4097/en-US/docs/Location.hostname";

console.log(anchor.hostname); // developer.mozilla.org
```

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

| Specification |
| --- |
| HTML Standard # dom-location-hostname-dev |

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

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


Location: reload() method - Web APIs

Location: reload() method
=========================

The **`reload()`** method of the `Location` interface reloads the current URL, like the Refresh button.

Syntax
------

```js
reload()
```

### Parameters

`forceGet`
Non-standard

Pass `true` to force a reload bypassing the cache. Defaults to `false`. Only supported in Firefox.

### Return value

None (`undefined`).

### Exceptions

`SecurityError` `DOMException`

Thrown if the origin of the script calling the method is not the same origin of the page originally described by the `Location` object, mostly when the script is hosted on a different domain.

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

| Specification |
| --- |
| HTML Standard # dom-location-reload-dev |

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

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

See also
--------

* The `Location` interface it belongs to.
* Similar methods: `Location.assign()` and
 `Location.replace()`.


Location: hash property - Web APIs

Location: hash property
=======================

 The **`hash`** property of the
 `Location` interface returns a string containing a
 `'#'` followed by the fragment identifier of the URL — the ID on the page
 that the URL is trying to target.

 The fragment is not URL decoded. If the URL does not
 have a fragment identifier, this property contains an empty string, `""`.

Value
-----

A string.

Examples
--------

```html
<a id="myAnchor" href="/en-US/docs/Location.href#Examples">Examples</a>
<script>
 const anchor = document.getElementById("myAnchor");
 console.log(anchor.hash); // Returns '#Examples'
</script>
```

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

| Specification |
| --- |
| HTML Standard # dom-location-hash-dev |

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

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


Location: origin property - Web APIs

Location: origin property
=========================

 The **`origin`** read-only property of
 the `Location` interface is a string containing the
 Unicode serialization of the origin of the represented URL.

That is:

* for URL using the `http` or `https`, the scheme followed by
 `'://'`, followed by the domain, followed by `':'`, followed by
 the port (the default port, `80` and `443` respectively, if
 explicitly specified);
* for URL using `file:` scheme, the value is browser dependent;
* for URL using the `blob:` scheme, the origin of the URL following
 `blob:`. E.g `"blob:https://mozilla.org"` will have
 `"https://mozilla.org".`

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

Value
-----

A string.

Examples
--------

```js
// On this page, returns the origin
const result = window.location.origin; // Returns:'https://developer.mozilla.org'
```

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

| Specification |
| --- |
| HTML Standard # dom-location-origin-dev |

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

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


Location: assign() method - Web APIs

Location: assign() method
=========================

 The **`assign()`** method of the `Location`
 interface causes the window to load
 and display the document at the URL specified. After the navigation occurs, the user can
 navigate back to the page that called `Location.assign()` by pressing the "back" button.

Syntax
------

```js
assign(url)
```

### Parameters

`url`

A string containing the URL of the page to navigate to; for example, an absolute URL such as `https://developer.mozilla.org/en-US/docs/Web/API/Location/reload`, or a relative URL — such as `"/Web` (just a path, for navigating to another document at the same origin) or `#specifications` (just a fragment string, for navigating to some part of the same page), and so on.

### Exceptions

`SecurityError` `DOMException`

Thrown if the origin of the script calling the method is not the same origin of the page originally described by the `Location` object, mostly when the script is hosted on a different domain.

`SyntaxError` `DOMException`

Thrown if the provided `url` parameter is not a valid URL.

### Return value

None (`undefined`).

Examples
--------

```js
// Navigate to the Location.reload article
window.location.assign(
  "https://developer.mozilla.org/en-US/docs/Web/API/Location/reload",
);

// Then navigate to its Specifications section
window.location.assign("#specifications");

// Eventually navigate to https://developer.mozilla.org/en-US/docs/Web
window.location.assign("/Web");
```

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

| Specification |
| --- |
| HTML Standard # dom-location-assign-dev |

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

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

See also
--------

* The `Location` interface it belongs to.
* Similar methods: `Location.replace()` and
 `Location.reload()`.


Location: replace() method - Web APIs

Location: replace() method
==========================

 The **`replace()`** method of the `Location`
 interface replaces the current resource with the one at the provided URL. The difference
 from the `assign()` method is that after using
 `replace()` the current page will not be saved in session `History`,
 meaning the user won't be able to use the *back* button to navigate to it.

Syntax
------

```js
replace(url)
```

### Parameters

`url`

A string containing the URL of the page to navigate to.

### Exceptions

`SyntaxError` `DOMException`

Thrown if the provided `url` parameter is not a valid URL.

### Return value

None (`undefined`).

Examples
--------

```js
// Navigate to the Location.reload article by replacing this page
window.location.replace(
  "https://developer.mozilla.org/en-US/docs/Web/API/Location.reload",
);
```

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

| Specification |
| --- |
| HTML Standard # dom-location-replace-dev |

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

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

See also
--------

* The `Location` interface it belongs to.
* Similar methods: `Location.assign()` and
 `Location.reload()`.


SharedStorageRunOperation: run() method - Web APIs

SharedStorageRunOperation: run() method
=======================================

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

 The **`run()`** method of the
 `SharedStorageRunOperation` interface defines the structure to which the `run()` method defined inside a Run output gate operation should conform.

Syntax
------

```js
run(data)
```

### Parameters

`data`

An object representing any data required for executing the operation.

### Return value

A `Promise` that fulfills with `undefined`.

Examples
--------

See the main `SharedStorageRunOperation` page for an example.

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

| Specification |
| --- |
| Shared Storage API # dom-sharedstoragerunoperation-run |

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

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

See also
--------

* Shared Storage API


RTCPeerConnectionIceEvent: RTCPeerConnectionIceEvent() constructor - Web APIs

RTCPeerConnectionIceEvent: RTCPeerConnectionIceEvent() constructor
==================================================================

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

Syntax
------

```js
new RTCPeerConnectionIceEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `icecandidate`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`candidate`

 A `RTCIceCandidate` representing the ICE candidate being concerned by the event.
 If `null`, the event indicates the end of candidate gathering.

`url`

 A string containing the URL of the STUN or TURN server which was used to gather the candidate.
 If the candidate was not gathered by a STUN or TURN server,
 this value must be `null`, which is also the default value.

### Return value

A new `RTCPeerConnectionIceEvent` object, configured as specified in the provided options.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnectioniceevent-constructor |

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

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

See also
--------

* WebRTC
* Its usual target: `RTCPeerConnection`.


RTCPeerConnectionIceEvent: candidate property - Web APIs

RTCPeerConnectionIceEvent: candidate property
=============================================

 The read-only **`candidate`** property
 of the `RTCPeerConnectionIceEvent` interface returns the
 `RTCIceCandidate` associated with the event.

Value
-----

 An `RTCIceCandidate` object representing the ICE candidate that has been
 received, or `null` to indicate that there are no further candidates for this
 negotiation session.

Example
-------

```js
pc.onicecandidate = (ev) => {
  alert(
    `The ICE candidate (transport address: '${ev.candidate.candidate}') has been added to this connection.`,
  );
};
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnectioniceevent-candidate |

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

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

See also
--------

* `icecandidate`
* `RTCPeerConnection`


PresentationAvailability: value property - Web APIs

PresentationAvailability: value property
========================================

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

The **`value`** attribute *MUST* return the last value from which it was set. The value is updated by the monitor the list of available presentation displays algorithm.

The `onchange` attribute is an event handler whose corresponding event handler event type is `change`.

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

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


CharacterBoundsUpdateEvent: rangeStart property - Web APIs

CharacterBoundsUpdateEvent: rangeStart property
===============================================

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

The **`CharacterBoundsUpdateEvent.rangeStart`** read-only property represents the offset of the first character within the editable text region for which the operating system needs the bounds.

Value
-----

A `Number`.

Examples
--------

### Reading the `rangeStart` value

This example shows how to use the `characterboundsupdate` event and read the value of the `rangeStart` and `rangeEnd` properties.

```js
const editContext = new EditContext();
editorElement.editContext = editContext;

editContext.addEventListener("characterboundsupdate", (e) => {
  console.log(
    `The OS needs the bounds of the chars at ${e.rangeStart} - ${e.rangeEnd}.`,
  );
});
```

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

| Specification |
| --- |
| EditContext API # dom-characterboundsupdateevent-rangestart |

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

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


CharacterBoundsUpdateEvent: CharacterBoundsUpdateEvent() constructor - Web APIs

CharacterBoundsUpdateEvent: CharacterBoundsUpdateEvent() constructor
====================================================================

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

The **`CharacterBoundsUpdateEvent()`** constructor returns a new `CharacterBoundsUpdateEvent` object.

Syntax
------

```js
new CharacterBoundsUpdateEvent(type)
new CharacterBoundsUpdateEvent(type, options)
```

### Parameters

`type`

A string representing the type of the event. Possible values: `"characterboundsupdate"`.

`options` Optional

An optional object with the following properties:

`rangeStart`

A number to set the offset of the first character within the editable text region which this event applies to.

`rangeEnd`

A number to set the offset of the last character within the editable text region which this event applies to.

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

| Specification |
| --- |
| EditContext API # dom-characterboundsupdateevent-constructor |

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

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

See also
--------

* The `CharacterBoundsUpdateEvent` interface it belongs to.


CharacterBoundsUpdateEvent: rangeEnd property - Web APIs

CharacterBoundsUpdateEvent: rangeEnd property
=============================================

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

The **`CharacterBoundsUpdateEvent.rangeEnd`** read-only property represents the offset of the last character within the editable text region for which the operating system needs the bounds.

Value
-----

A `Number`.

Examples
--------

### Reading the `rangeEnd` value

This example shows how to use the `characterboundsupdate` event and read the value of the `rangeStart` and `rangeEnd` properties.

```js
const editContext = new EditContext();
editorElement.editContext = editContext;

editContext.addEventListener("characterboundsupdate", (e) => {
  console.log(
    `The OS needs the bounds of the chars at ${e.rangeStart} - ${e.rangeEnd}.`,
  );
});
```

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

| Specification |
| --- |
| EditContext API # dom-characterboundsupdateevent-rangestart |

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

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


Element: mouseup event - Web APIs

Element: mouseup event
======================

The **`mouseup`** event is fired at an `Element` when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it.

`mouseup` events are the counterpoint to `mousedown` events.

Syntax
------

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

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

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

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

A `MouseEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

MouseEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

Examples
--------

See `mousemove` event for example code.

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

| Specification |
| --- |
| UI Events # event-type-mouseup |
| HTML Standard # handler-onmouseup |

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

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

See also
--------

* Introduction to events
* `mousedown`
* `mouseup`
* `mousemove`
* `click`
* `dblclick`
* `mouseover`
* `mouseout`
* `mouseenter`
* `mouseleave`
* `contextmenu`


Element: ariaRelevant property - Web APIs

Element: ariaRelevant property
==============================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`ariaRelevant`** property of the `Element` interface reflects the value of the `aria-relevant` attribute, which indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. This is used to describe what changes in an `aria-live` region are relevant and should be announced.

Value
-----

A string containing one or more of the following values, space separated:

`"additions"`

Additions of Element Nodes within the live region should be considered relevant.

`"removals"`

Deletion of Nodes from the live region should be considered relevant.

`"text"`

Changes to the textual content of existing nodes should be considered relevant.

`"all"`

Equivalent to `"additions removals text"`.

Examples
--------

In this example the `aria-relevant` attribute on the element with an ID of `text` is set to "all". Using `ariaRelevant` we update the value to "text".

```html
<div
 id="clock"
 role="timer"
 aria-live="polite"
 aria-atomic="true"
 aria-relevant="all"></div>
```

```js
let el = document.getElementById("clock");
console.log(el.ariaRelevant); // all
el.ariaRelevant = "text";
console.log(el.ariaRelevant); // text
```

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

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


Element: closest() method - Web APIs

Element: closest() method
=========================

The **`closest()`** method of the `Element` interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.

Syntax
------

```js
closest(selectors)
```

### Parameters

`selectors`

A string of valid CSS selector to match the `Element` and its ancestors against.

### Return value

The closest ancestor `Element` or itself, which matches the `selectors`. If there are no such element, `null`.

### Exceptions

`SyntaxError` `DOMException`

Thrown if the `selectors` is not a valid CSS selector.

Examples
--------

### HTML

```html
<article>
  <div id="div-01">
    Here is div-01
    <div id="div-02">
      Here is div-02
      <div id="div-03">Here is div-03</div>
    </div>
  </div>
</article>
```

### JavaScript

```js
const el = document.getElementById("div-03");

// the closest ancestor with the id of "div-02"
console.log(el.closest("#div-02")); // <div id="div-02">

// the closest ancestor which is a div in a div
console.log(el.closest("div div")); // <div id="div-03">

// the closest ancestor which is a div and has a parent article
console.log(el.closest("article > div")); // <div id="div-01">

// the closest ancestor which is not a div
console.log(el.closest(":not(div)")); // <article>
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-closest① |

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

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

### Compatibility notes

* In Edge 15-18 `document.createElement(tagName).closest(tagName)` will
 return `null` if the element is not first connected (directly or
 indirectly) to the context object, for example the `Document` object in
 the case of the normal DOM.
See also
--------

* CSS selectors module
* Other `Element` methods that take selectors: `Element.querySelector()`, `Element.querySelectorAll()`, and `Element.matches()`.


Element: fullscreenchange event - Web APIs

Element: fullscreenchange event
===============================

The `fullscreenchange` event is fired immediately after an `Element` switches into or out of fullscreen mode.

This event is sent to the `Element` which is transitioning into or out of fullscreen mode.

To find out whether the `Element` is entering or exiting fullscreen mode, check the value of `Document.fullscreenElement`: if this value is `null` then the element is exiting fullscreen mode, otherwise it is entering fullscreen mode.

This event is not cancelable.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

In this example, a handler for the `fullscreenchange` event is added to the element whose ID is `fullscreen-div`.

If the user clicks on the "Toggle Fullscreen Mode" button, the `click` handler will toggle fullscreen mode for the `div`. If `document.fullscreenElement` has a value it will exit fullscreen mode. If not, the div will be placed into fullscreen mode.

Remember that by the time the `fullscreenchange` event is handled, the status of the element has already changed. So if the change is to fullscreen mode, `document.fullscreenElement` will point to the element that is now in fullscreen mode. On the other hand, if `document.fullscreenElement` is null, fullscreen mode has been canceled.

What that means to the example code is that, if an element is currently in fullscreen mode, the `fullscreenchange` handler logs the `id` of the fullscreen element to the console. If `document.fullscreenElement` is null, the code logs a message that the change is to leave fullscreen mode.

### HTML

```html
<h1>fullscreenchange event example</h1>
<div id="fullscreen-div">
  <button id="toggle-fullscreen">Toggle Fullscreen Mode</button>
</div>
```

### JavaScript

```js
function fullscreenchanged(event) {
  // document.fullscreenElement will point to the element that
  // is in fullscreen mode if there is one. If not, the value
  // of the property is null.
  if (document.fullscreenElement) {
    console.log(
      `Element: ${document.fullscreenElement.id} entered fullscreen mode.`,
    );
  } else {
    console.log("Leaving fullscreen mode.");
  }
}

const el = document.getElementById("fullscreen-div");

el.addEventListener("fullscreenchange", fullscreenchanged);
// or
el.onfullscreenchange = fullscreenchanged;

// When the toggle button is clicked, enter/exit fullscreen
document
  .getElementById("toggle-fullscreen")
  .addEventListener("click", (event) => {
    if (document.fullscreenElement) {
      // exitFullscreen is only available on the Document object.
      document.exitFullscreen();
    } else {
      el.requestFullscreen();
    }
  });
```

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

| Specification |
| --- |
| Fullscreen API Standard # handler-document-onfullscreenchange |

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

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

See also
--------

* Document: fullscreenchange event
* Element: fullscreenerror event
* Fullscreen API
* Guide to the Fullscreen API


Element: classList property - Web APIs

Element: classList property
===========================

 The **`Element.classList`** is a read-only property that
 returns a live `DOMTokenList` collection of the `class`
 attributes of the element. This can then be used to manipulate the class list.

 Using `classList` is a convenient alternative to accessing an element's list
 of classes as a space-delimited string via `element.className`.

Value
-----

 A `DOMTokenList` representing the contents of the element's
 `class` attribute. If the `class` attribute is not set or empty,
 it returns an empty `DOMTokenList`, i.e. a `DOMTokenList` with
 the `length` property equal to `0`.

Although the `classList` property itself is read-only, you can modify its associated `DOMTokenList` using the `add()`, `remove()`, `replace()`, and `toggle()` methods.

You can test whether the element contains a given class using the `classList.contains()` method.

Examples
--------

```js
const div = document.createElement("div");
div.className = "foo";

// our starting state: <div class="foo"></div>
console.log(div.outerHTML);

// use the classList API to remove and add classes
div.classList.remove("foo");
div.classList.add("anotherclass");

// <div class="anotherclass"></div>
console.log(div.outerHTML);

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");

// add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10);

// false
console.log(div.classList.contains("foo"));

// add or remove multiple classes
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");

// add or remove multiple classes using spread syntax
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);

// replace class "foo" with class "bar"
div.classList.replace("foo", "bar");
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-classlist① |

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

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

See also
--------

* `element.className`
* `DOMTokenList`
* `classList.js` (a cross-browser JavaScript polyfill that fully implements `element.classList`)


Element: animationstart event - Web APIs

Element: animationstart event
=============================

The **`animationstart`** event is fired when a CSS Animation has started. If there is an `animation-delay`, this event will fire once the delay period has expired. A negative delay will cause the event to fire with an `elapsedTime` equal to the absolute value of the delay (and, correspondingly, the animation will begin playing at that time index into the sequence).

Syntax
------

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

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

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

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

An `AnimationEvent`. Inherits from `Event`.

Event

AnimationEventEvent properties
----------------

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

`AnimationEvent.animationName` Read only

A string containing the value of the `animation-name` that generated the animation.

`AnimationEvent.elapsedTime` Read only

A `float` giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an `animationstart` event, `elapsedTime` is `0.0` unless there was a negative value for `animation-delay`, in which case the event will be fired with `elapsedTime` containing `(-1 * delay)`.

`AnimationEvent.pseudoElement` Read only

A string, starting with `'::'`, containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: `''`.

Examples
--------

This listens for the `animationstart` event and logs a message when it is fired:

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

animated.addEventListener("animationstart", () => {
  console.log("Animation started");
});
```

The same, but using `onanimationstart`:

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

animated.onanimationstart = () => {
  console.log("Animation started");
};
```

### Live example

#### HTML

```html
<div class="animation-example">
  <div class="container">
    <p class="animation">You chose a cold night to visit our planet.</p>
  </div>
  <button class="activate" type="button">Activate animation</button>
  <div class="event-log"></div>
</div>
```

#### CSS

```css
.container {
  height: 3rem;
}

.event-log {
  width: 25rem;
  height: 2rem;
  border: 1px solid black;
  margin: 0.2rem;
  padding: 0.2rem;
}

.animation.active {
  animation-duration: 2s;
  animation-name: slidein;
  animation-iteration-count: 2;
}

@keyframes slidein {
  from {
    transform: translateX(100%) scaleX(3);
  }
  to {
    transform: translateX(0) scaleX(1);
  }
}
```

#### JavaScript

```js
const animation = document.querySelector("p.animation");
const animationEventLog = document.querySelector(
  ".animation-example>.event-log",
);
const applyAnimation = document.querySelector(
  ".animation-example>button.activate",
);
let iterationCount = 0;

animation.addEventListener("animationstart", () => {
  animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `;
});

animation.addEventListener("animationiteration", () => {
  iterationCount++;
  animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `;
});

animation.addEventListener("animationend", () => {
  animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`;
  animation.classList.remove("active");
  applyAnimation.textContent = "Activate animation";
});

animation.addEventListener("animationcancel", () => {
  animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`;
});

applyAnimation.addEventListener("click", () => {
  animation.classList.toggle("active");
  animationEventLog.textContent = "";
  iterationCount = 0;
  const active = animation.classList.contains("active");
  applyAnimation.textContent = active
    ? "Cancel animation"
    : "Activate animation";
});
```

#### Result

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

| Specification |
| --- |
| CSS Animations Level 1 # eventdef-globaleventhandlers-animationstart |

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

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

See also
--------

* CSS Animations
* Using CSS Animations
* `AnimationEvent`
* Related events: `animationend`, `animationiteration`, `animationcancel`


Element: ariaLevel property - Web APIs

Element: ariaLevel property
===========================

The **`ariaLevel`** property of the `Element` interface reflects the value of the `aria-level` attribute, which defines the hierarchical level of an element within a structure.

**Note:** Where possible use an HTML h1 or other correct heading level as these have built in semantics and do not require ARIA attributes.

Value
-----

A string containing an integer.

Examples
--------

In this example the `aria-level` attribute on the element with an ID of `main-heading` is set to "1". Using `ariaLevel` we update the value to "2".

```html
<div role="heading" id="main-heading" aria-level="1">
  This is a main page heading
</div>
```

```js
let el = document.getElementById("main-heading");
console.log(el.ariaLevel); // "1"
el.ariaLevel = "2";
console.log(el.ariaLevel); // "2"
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-arialevel |

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

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

See also
--------

* ARIA: heading role


Element: ariaKeyShortcuts property - Web APIs

Element: ariaKeyShortcuts property
==================================

The **`ariaKeyShortcuts`** property of the `Element` interface reflects the value of the `aria-keyshortcuts` attribute, which indicates keyboard shortcuts that an author has implemented to activate or give focus to an element.

Value
-----

A string.

Examples
--------

In this example the `aria-keyshortcuts` attribute on the element with an ID of `skip-link` is set to "Alt+Shift+A". Using `ariaKeyShortcuts` we update the value to "Alt+Shift+M".

```html
<a id="skip-link" href="#content" aria-keyshortcuts="Alt+Shift+A">
  Skip to content
</a>
```

```js
let el = document.getElementById("saveChanges");
console.log(el.ariaKeyShortcuts); // "Alt+Shift+A"
el.ariaKeyShortcuts = "Alt+Shift+M";
console.log(el.ariaKeyShortcuts); // "Alt+Shift+M"
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariakeyshortcuts |

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

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


Element: ariaDisabled property - Web APIs

Element: ariaDisabled property
==============================

The **`ariaDisabled`** property of the `Element` interface reflects the value of the `aria-disabled` attribute, which indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

**Note:** Where possible, use the `<input>` element with `type="button"` or the `<button>` element — because those elements have built in semantics and do not require ARIA attributes.

Value
-----

A string with one of the following values:

`"true"`

The element and all focusable descendants are disabled, but perceivable, and their values cannot be changed by the user.

`"false"`

The element is enabled.

Examples
--------

In this example the `aria-disabled` attribute on the element with an ID of `saveChanges` is set to "true" indicating that this input is currently disabled. Using `ariaDisabled` we update the value to "false".

```html
<div id="saveChanges" tabindex="0" role="button" aria-disabled="true">Save</div>
```

```js
let el = document.getElementById("saveChanges");
console.log(el.ariaDisabled); // "true"
el.ariaDisabled = "false";
console.log(el.ariaDisabled); // "false"
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariadisabled |

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

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


Element: ariaDescription property - Web APIs

Element: ariaDescription property
=================================

The **`ariaDescription`** property of the `Element` interface reflects the value of the `aria-description` attribute, which defines a string value that describes or annotates the current element.

Value
-----

A string.

Examples
--------

In this example the `aria-description` attribute on the element with an ID of `close-button` is set to the string "A longer description of the function of this element". Using `ariaDescription` we can update the value.

```html
<button
 aria-label="Close"
 aria-description="A longer description of the function of this element"
 id="close-button">
  X
</button>
```

```js
let el = document.getElementById("close-button");
console.log(el.ariaDescription); // "A longer description of the function of this element"
el.ariaDescription = "A different description";
console.log(el.ariaDescription); // "A different description"
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariadescription |

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

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