DEV Community

pwnkdm
pwnkdm

Posted on

1

Fun with JavaScript: Changing Page Titles Dynamically

Have you ever noticed how some websites change their page title when you switch tabs? It's a simple yet clever trick to grab a user's attention. Let’s explore how you can achieve this effect using just a few lines of JavaScript.

When tab changed tab title changed to
When tab is in visible state title changed to

The Magic Behind visibilitychange

The visibilitychange event in JavaScript fires whenever a user switches between tabs or minimizes the browser window. Using this, we can dynamically update the document title based on the tab’s visibility state.

Here's the code:



document.addEventListener("visibilitychange", function () {
    if (document.hidden) {
      document.title = "I'm a lonely tab 😢";
    } else {
      document.title = "Welcome back 😊";
    }
  });


Enter fullscreen mode Exit fullscreen mode

How It Works

  1. The document.addEventListener listens for the "visibilitychange" event.

  2. When the tab is hidden (document.hidden is true), the title changes to "I'm a lonely tab 😢".

  3. When the user returns to the tab, the title is restored to "Welcome back 😊".

Why Use This?

Engagement: This trick can remind users to return to your site.

Branding: Custom messages can enhance your site's personality.

User Experience: Fun, interactive elements make websites more enjoyable.

Try adding this snippet to your website and see how it works!

Top comments (0)