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.
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 😊";
}
});
How It Works
The document.addEventListener listens for the "visibilitychange" event.
When the tab is hidden (document.hidden is true), the title changes to "I'm a lonely tab 😢".
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)