JavaScript Reference ยท DOM: Events
The visibilitychange event
Reference for the visibilitychange event and document.visibilityState: pause work in background tabs, save data when a page is hidden and avoid unreliable unload events.
The visibilitychange event fires on document when the page becomes hidden or visible again. A page is hidden when the user switches to another tab, minimizes the window, locks the screen, or, on mobile, switches to another app. The current state is available at any time as document.visibilityState.
This is the right hook for being polite to the user's device (pause animations, polling and video in the background) and for saving data. When a page is hidden, it may be frozen or discarded without any further event, so visibilitychange to "hidden" is the last dependable moment to save or send data.
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") { saveDraft(); } });
Try it
Syntax
document.addEventListener("visibilitychange", listener); document.visibilityState // "visible" | "hidden" document.hidden // true when visibilityState is "hidden"
Values
visibilityState |
Meaning |
|---|---|
"visible" |
The page, or part of it, is on screen (the tab is active and the window is not minimized). |
"hidden" |
The page is not visible: another tab or app is in front, the window is minimized or the screen is locked. |
The event is not cancelable and does not bubble (it fires on document). It carries no extra properties. document.hidden is a shorter, older alias for visibilityState === "hidden".
Usage notes
- Use it instead of
unload.unloadandbeforeunloadare unreliable on mobile and block the back/forward cache. Send final analytics fromvisibilitychangewithnavigator.sendBeacon(). - Timers slow down in the background. Browsers throttle
setTimeout()andsetInterval()in hidden tabs, andrequestAnimationFrame()stops completely. Do not depend on timers for exact timing; compute elapsed time fromperformance.now()or timestamps. - A visible page can be partly covered. Another window can cover the browser without the state changing. Use
IntersectionObserverfor element-level visibility. - Media. Pause video and audio only if appropriate: music players and calls should keep playing while hidden.
- Check the state at startup. A page may load directly into a hidden background tab, so do not assume
"visible"on load, as the examples above checkdocument.hidden. - Page Lifecycle events. Chromium-based browsers also fire
freezeandresumeondocumentwhen the page is suspended and resumed. They are not available everywhere. pagehideis the companion for navigating away or closing; use both for complete coverage of "the user left".
Browser support
visibilitychange and document.visibilityState work in all current browsers. The freeze and resume Page Lifecycle events are limited to some browsers, so check a compatibility table.