YouTip LogoYouTip

Event Visibilitychange

## The `visibilitychange` Event The `visibilitychange` event is fired on the `Document` object when the content of its tab has become visible or has been hidden. This event is part of the **Page Visibility API**, which allows developers to detect the visibility state of a page. By tracking this event, you can optimize your web application's performance and resource usageβ€”for example, by pausing video playback, halting real-time data polling, or stopping animations when the user is not actively viewing the page. --- ## Syntax and Usage To listen for the `visibilitychange` event, register an event listener on the `document` object: ```javascript document.addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { // Code to run when the page becomes visible } else if (document.visibilityState === 'hidden') { // Code to run when the page becomes hidden } }); ``` ### The `document.visibilityState` Property When the event is triggered, you can check the current state of the document using `document.visibilityState`. It returns one of the following string values: * **`visible`**: The page content is at least partially visible. This means the tab is active and the window is not minimized. * **`hidden`**: The page content is not visible to the user. This can happen because the tab is in the background, the window is minimized, or the OS screen lock is active. --- ## Code Examples ### 1. Basic Example: Logging State Changes This example logs a message to the console whenever the user switches tabs or minimizes the browser window. ```javascript document.addEventListener('visibilitychange', () => { console.log(`The document is now: ${document.visibilityState}`); }); ``` ### 2. Practical Example: Pausing and Resuming a Video A common use case is pausing a video when the user switches tabs to save bandwidth and processing power, and resuming it when they return. ```javascript const videoElement = document.querySelector('video'); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { // Pause the video when the tab is hidden videoElement.pause(); console.log('Video paused because the page is hidden.'); } else if (document.visibilityState === 'visible') { // Play the video when the tab becomes visible again videoElement.play(); console.log('Video resumed because the page is visible.'); } }); ``` ### 3. Practical Example: Pausing Real-Time Data Polling If your application fetches live data (e.g., stock prices or chat messages) using `setInterval`, you can pause polling when the page is hidden to reduce server load. ```javascript let pollingInterval; function startPolling() { pollingInterval = setInterval(() => { console.log('Fetching live data from server...'); // fetch('/api/live-data') }, 5000); } function stopPolling() { clearInterval(pollingInterval); } // Start polling initially startPolling(); // Adjust polling based on page visibility document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { stopPolling(); console.log('Polling paused.'); } else { startPolling(); console.log('Polling resumed.'); } }); ``` --- ## Browser Support The `visibilitychange` event is widely supported across all modern desktop and mobile browsers. | Event | Chrome | Edge/IE | Firefox | Safari | Opera | | :--- | :--- | :--- | :--- | :--- | :--- | | **`visibilitychange`** | 62+ | 18+ | 56+ | 14.1+ | 49+ | ### Important Considerations 1. **Energy-Saving Modes**: Some mobile devices or desktop operating systems may put background tabs into a deep sleep or freeze state to save battery. In these cases, the `visibilitychange` event will fire as the page goes into the background, but timers (like `setTimeout` or `setInterval`) may be throttled or paused entirely by the browser. 2. **Reliability for Analytics**: If you want to track user sessions or save application state before a user closes the page, the `visibilitychange` event is highly recommended. It is much more reliable than the `unload` or `beforeunload` events, especially on mobile browsers where tabs are often discarded without firing unload events.
← Git SwitchRegexp Metachar B β†’