Document: visibilitychange event

Baseline Widely available

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

The visibilitychange event is fired at the document when the contents of its tab have become visible or have been hidden.

The event is not cancelable.

Syntax

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

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

onvisibilitychange = (event) => {};

Event type

A generic Event.

Usage notes

The event doesn't include the document's updated visibility status, but you can get that information from the document's visibilityState property.

This event fires with a visibilityState of hidden when a user navigates to a new page, switches tabs, closes the tab, minimizes or closes the browser, or, on mobile, switches from the browser to a different app. Transitioning to hidden is the last event that's reliably observable by the page, so developers should treat it as the likely end of the user's session (for example, for sending analytics data).

The transition to hidden is also a good point at which pages can stop making UI updates and stop any tasks that the user doesn't want to have running in the background.

Examples

Pausing music on transitioning to hidden

This example pauses playing audio when the page is hidden and resumes playing when the page becomes visible again. For a full example, see the Page Visibility API: Pausing audio on page hide documentation.

js
document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    playingOnHide = !audio.paused;
    audio.pause();
  } else {
    // Resume playing if audio was "playing on hide"
    if (playingOnHide) {
      audio.play();
    }
  }
});

Sending end-of-session analytics on transitioning to hidden

This example treats the transition to hidden as the end of the user's session, and sends the appropriate analytics using the Navigator.sendBeacon() API:

js
document.onvisibilitychange = () => {
  if (document.visibilityState === "hidden") {
    navigator.sendBeacon("/log", analyticsData);
  }
};

Specifications

Specification
HTML
# event-visibilitychange
HTML
# handler-onvisibilitychange

Browser compatibility

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
visibilitychange event

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Requires a vendor prefix or different name for use.
Has more compatibility info.

See also