onvisibilitychange

The onvisibilitychange event attribute defines a JavaScript function to run when the visibility state of a document changes, showing whether the page is in the foreground or background.

onvisibilitychange Event

The onvisibilitychange property serves as an event handler that triggers when a visibilitychange event occurs on the document.

Syntax

Utilize the event name in methods such as addEventListener() or by assigning it to an event handler property.

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

Example

Pausing Music When the Page Becomes Hidden

This example stops audio playback when the page is no longer visible and resumes it when the page becomes active again. For a complete example, refer to the Page Visibility API: Pausing Audio on Page Hide documentation.

script.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 session-end analytics when transitioning to a hidden state

This example considers the transition to a hidden state as the session's end and utilizes the Navigator.sendBeacon() API to send the relevant analytics.

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

Conclusion

The onvisibilitychange event enables the execution of a function when a document's visibility state changes, determining whether the page is in the foreground or background. This is particularly useful for detecting when a user switches tabs or minimizes the browser, allowing you to adjust page behavior accordingly.