Recently, I wrote a really cool piece of JavaScript code. I tried it on my own blog, and the effect was awesome!
If your blog supports custom JS, you can try it too to make your pages more lively and interesting.
What Can It Do?
When the user switches to another tab or minimizes the browser, the title automatically changes to "Don't wander too far..." to "retain" the user. When the user returns to the page, the title enthusiastically changes to "Yay, you're back! ヾ (•ω•`)o", and after two seconds, it automatically reverts to the original title.
Pretty cool, right? Here's the code!
Code Implementation
// Define the original title
const originalTitle = document.title;
let timeoutId; // Used to store the timer ID
// Listen for page visibility changes
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
// Change the title when the page is not visible
document.title = "Don't wander too far...";
// Clear any existing timer
clearTimeout(timeoutId);
} else {
// When the page is visible, change the title after a 2-second delay
document.title = "Yay, you're back! ヾ (•ω•`)o";
// Revert to the original title after another 2 seconds
timeoutId = setTimeout(() => {
document.title = originalTitle;
}, 2000);
}
});
Technical Breakdown
1. document.title
This is a simple yet powerful property used to read or change the title content on the webpage tab. By dynamically assigning a value, we make the title "come alive."
2. document.hidden
This property comes from the browser's Visibility API and is used to detect whether the page is in a hidden state. When the user switches tabs or minimizes the browser, it becomes true; when the user returns, it changes back to false.
3. visibilitychange Event
This event is triggered when the page visibility changes, making it perfect for implementing this kind of "user behavior detection" functionality.
4. setTimeout and clearTimeout
setTimeoutallows us to delay the title restoration by a few seconds when the user returns, making it feel more natural.clearTimeoutensures that no redundant delayed operations pile up, preventing logic conflicts.
Features and Limitations
Advantages:
- Simple implementation logic, intuitive code.
- Manages state directly through global variables, quickly achieving the functionality.
Limitations:
- Uses global variables
originalTitleandtimeoutId, which may conflict with other code. - Does not clean up event listeners, which could lead to potential memory leaks when the page is unloaded.
- Uses global variables
Improved Version: Suggestion from Commenter liuzhen932
liuzhen932 proposed a more modular version that encapsulates the code in an immediately invoked function expression (IIFE) and adds an event cleanup mechanism. Here's the improved code:
(function () {
"use strict";
// Save the original title for later restoration
const originalTitle = document.title;
// Store the timer ID to prevent multiple timers from conflicting
let timeoutId;
// Handle page visibility change logic
function handleVisibilityChange() {
// Clear any previous timer
clearTimeout(timeoutId);
if (document.hidden) {
// When the page is not visible, set the title
document.title = "Don't wander too far...";
} else {
// When the page is visible, first set a notification title
document.title = "Yay, you're back! ヾ(•ω•`)o";
// Delay 2 seconds before restoring the original title
timeoutId = setTimeout(() => {
document.title = originalTitle;
}, 2000);
}
}
// Cleanup logic when the page is about to unload
function beforeUnloadListener() {
// Remove the visibility change event listener to avoid memory leaks
document.removeEventListener("visibilitychange", handleVisibilityChange);
}
// Bind the page visibility change event
document.addEventListener("visibilitychange", handleVisibilityChange);
// Remove the related event listener before the page unloads
window.addEventListener("beforeunload", beforeUnloadListener);
})();
Improvements
- Modular Design:
- Uses an immediately invoked function expression (IIFE) to avoid global variable pollution.
- Event Cleanup:
- Removes the
visibilitychangelistener when the page unloads, reducing the risk of memory leaks.
- Removes the
- Conciseness:
- Uses ternary operators and logical short-circuiting to make the code more compact.
Where to Actually Use It?
I don't know, it's just fun. It could be an Easter egg on your blog, or maybe a reminder of some sort—it depends on what you use it for!
Small Tips
- Use in Moderation: Frequent title changes can be annoying, so control the trigger frequency.
- Compatibility Issues: Although modern browsers almost all support the Visibility API, if your user base includes users on older browsers, it's best to handle compatibility.
I'll continue sharing code like this in the future. Feel free to use it as you like. If you can leave your blog in the comments, I might go check it out (or not).