You can detect whether a user is looking at your page or is currently on another tab using onvisibilitychange and visibilityState
This is a super useful feature and can help ensure users do not miss out on important content when they move to a different tab. For example you can use it to pause a video that is currently playing and only restart it when the user clicks back onto your site.
The very simple example below changes the document title depending on whether the page is currently visible, but this can easily be modified to change other parts of your site.
<html>
<body>
<h1>Welcome</h1>
<script>
document.onvisibilitychange = function () {
document.visibilityState === "visible"
? (document.title = "π Hello")
: (document.title = "π Bye!");
};
</script>
</body>
</html>
If you enjoyed this little snippet you can follow me on Twitter where I regularly post bite size tips relating to HTML, CSS and JavaScript.
Top comments (4)
'onvisibilitychange' is now supported in most modern browsers. But people around me doesn't much care about updating browsers. So, this snippet might not always give desired results.
No worries, Check out this library with various polyfills:
pagalprogrammer / funtabify
A javascript library to change page title (text visible on tab) when user switches tab of a browser.
funtabify v1.0
A javascript library to change page title (text visible on tab) when user switches tab of a browser.
Requirement
Usage
Licenced under GNU GPLv3
or get a ready to use production copy.
Catch me on twitter
i'm really like this kinds of tricks or tips
Excellent tip
Thanks, I'll use that for my next project!