loading...
Cover image for 👀 Detect when your site is visible to users

👀 Detect when your site is visible to users

iainfreestone profile image Iain Freestone Updated on ・1 min read

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.

Posted on May 24 by:

iainfreestone profile

Iain Freestone

@iainfreestone

A Web developer from Hampshire in the south of England.

Discussion

markdown guide
 

'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:

GitHub logo pagalprogrammer / funtabify

A javascript library to change page title (text visible on tab) when user switches tab of a browser.

funtabify v1.0

GitHub GitHub top language GitHub file size in bytes GitHub release (latest by date)

A javascript library to change page title (text visible on tab) when user switches tab of a browser.

Requirement

  1. jQuery Library

Usage

  1. Download Minified Funtabify Library
  2. Include it at the end of your webpage before closing body tag:
 <script src="<path-to-funatbify.min.js"></script>
 <script>new funtabify("<Text-to-display-on-tab-switch>");</script>

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

 

Thanks, I'll use that for my next project!