Have you ever noticed how when you switch to another tab, the video or animation you were watching suddenly pauses, and when you come back - it resumes automatically? Or how some pages seem to pause their activity the moment you move away, and pick up right where they left off when you return?
That’s all because of the Page Visibility API - specifically, the visibilitychange event. This simple event lets a web page know when it’s visible to the user or hidden in the background, so it can act smarter - like saving battery, pausing timers, or deferring background tasks until you return.
Here’s the simplest possible example that shows exactly how it works 👇
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tab Visibility Demo</title>
</head>
<body>
<h1>Switch tabs to see the magic ✨</h1>
<script>
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
console.log('👋 You left the tab! The page is now hidden.');
} else {
console.log('👀 Welcome back! The page is visible again.');
}
});
</script>
</body>
</html>
✅ How to try it:
- Copy this into a file like tab-visibility.html.
- Open it in your browser.
- Open DevTools (F12 → Console).
- Switch to another tab → “👋 You left the tab!”
- Come back → “👀 Welcome back!”
React version (just as easy)
import { useEffect } from 'react';
export default function App() {
useEffect(() => {
function handleVisibility() {
if (document.hidden) {
console.log('👋 You left the tab!');
} else {
console.log('👀 Welcome back!');
}
}
document.addEventListener('visibilitychange', handleVisibility);
return () => document.removeEventListener('visibilitychange', handleVisibility);
}, []);
return <h1>Switch tabs and check your console 👀</h1>;
}
This tiny event is behind so much of what makes the web feel smooth - from pausing media and animations to keeping your apps efficient and responsive. And the best part? It only takes a few lines of JavaScript!
Top comments (0)