DEV Community

Cover image for πŸ‘€ Detect when your site is visible to users
Iain Freestone
Iain Freestone

Posted on • Edited on • Originally published at iainfreestone.com

πŸ‘€ Detect when your site is visible to users

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>
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
ankitbeniwal profile image
Ankit Beniwal • Edited

'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

Collapse
 
mosfa profile image
open

i'm really like this kinds of tricks or tips

Collapse
 
raagpc profile image
raag pc

Excellent tip

Collapse
 
seanolad profile image
Sean

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