Page Visibility API
In one line
The Page Visibility API lets you know when the page tab is hidden (switched away or minimized) so you can pause work.
In simple words
The Page Visibility API tells you whether the page is currently visible to the user. When the user switches to another tab or minimizes the browser, document.visibilityState becomes "hidden" and a visibilitychange event fires. When they return, it becomes "visible".
This is valuable for resource management: pause a video or animation when the tab is hidden (no point rendering frames no one sees), throttle polling or analytics, stop a game loop, or reduce battery-draining work. It also avoids misleading metrics — you can pause time-on-page tracking when the tab is hidden.
The API is simple: read document.visibilityState ("visible" or "hidden") and listen for the visibilitychange event. document.hidden is a boolean shortcut. Combine with requestAnimationFrame for automatic pausing of render loops.
Example
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
console.log("Tab hidden — pausing video");
video.pause();
} else {
console.log("Tab visible — resuming");
video.play();
}
});When the user switches away, document.hidden becomes true and the video pauses. Returning to the tab resumes playback.
Related terms
Related Resources
Related Lessons
- Page Lifecycle
Learn visibility and lifecycle.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.