Published on

👀 Detect when your site is visible to users

Authors

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>