# Page Visibility API

The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.

## 1. Why use it?

When a user minimizes the window or switches to another tab, the API sends a `visibilitychange` event. You can use this to:
*   Pause videos or audio.
*   Stop expensive animations or calculations.
*   Stop polling a server for data.
*   Save battery and CPU usage on the user's device.

## 2. Properties

The API adds two read-only properties to the `document` object:

*   **`document.hidden`**: Returns `true` if the page is in a state considered hidden to the user, and `false` otherwise.
*   **`document.visibilityState`**: Returns a string denoting the visibility state of the document.
    *   `visible`: The page content may be at least partially visible.
    *   `hidden`: The page content is not visible to the user (minimized or background tab).

## 3. The `visibilitychange` Event

This event is fired at the document when the contents of its tab have become visible or have been hidden.

```javascript
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "visible") {
    console.log("Tab is active");
    // Resume music/video/animation
  } else {
    console.log("Tab is hidden");
    // Pause music/video/animation
  }
});
```

## 4. Practical Example: Audio Player

```javascript
const audio = document.querySelector("audio");

// Pause audio when the user switches tabs
document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    audio.pause();
  } else {
    // Only resume if it was playing before? 
    // (Logic depends on app requirements)
    audio.play(); 
  }
});
```

This simple addition ensures your website doesn't annoy users by playing sound when they aren't looking at it.

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/events]]