Easy Tab Activity Checker Using JavaScript

Easy Tab Activity Checker Using JavaScript

ยท

2 min read

Today, I want to share a simple JavaScript script that you can use to check whether the current browser tab is active or not. Imagine having a website that does something special when the user is actively looking at it, and something different when they switch to another tab. Sounds cool, right? Let's dive in!

Why is Tab Activity Important?

Imagine you have a web application, and you want to pause a video or update some information only when the user is actively looking at your page. Checking tab activity helps you achieve just that. Let's get started with the code!

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tab Activity Checker</title>
  </head>
  <body>
    <script>
      // Function to handle tab activity changes
      function handleVisibilityChange() {
        if (document.hidden) {
          document.title = "Come back!"; // Change page title when the tab is not active
        } else {
          document.title = "Active"; // Change page title when the tab becomes active
        }
      }

      // Adding event listener for visibility change
      document.addEventListener("visibilitychange", handleVisibilityChange);
    </script>
  </body>
</html>

Understanding the Code

  1. We start by creating a simple HTML file with a script tag inside the body.

  2. The handleVisibilityChange function is where the magic happens. It's triggered whenever the visibility of the document changes.

  3. Inside this function, we check if document.hidden is true or false. If it's true, that means the tab is not active, and we show an alert saying 'Come back!'. If it's false, the tab is active, and we show an alert saying 'Active'.

  4. We add an event listener to the document for the 'visibilitychange' event, which fires every time the visibility state of the document changes.

Testing the Code

  1. Save the HTML file with an appropriate name, for example, tab_activity_checker.html.

  2. Open the file in your web browser.

  3. Switch between tabs and observe the alerts. You should see 'Active' when the tab is active and 'Come back!' when it's not.

And there you have it! A simple script to check if the current tab is active or not, using JavaScript. Feel free to incorporate this into your web projects to enhance user experience. Happy coding!

ย