Recently, I wrote a very cool piece of JavaScript code, and I tried it on my blog with fantastic results!
If your blog supports custom JS, you can give it a try to make your page more lively and interesting.
What can it do?#
When users switch to other tabs or minimize the browser, the title automatically changes to "Don't go too far, hey..." to "keep" the user; when the user returns to the page, the title enthusiastically displays "Yay, you're back! ヾ (・ω・`) o", and after two seconds, it will automatically revert to the original title.
Isn't that cool? Let's see the code!
Code Implementation#
// Define the original title
const originalTitle = document.title;
let timeoutId; // Used to store the timer ID
// Listen for visibility changes of the page
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
// Change the title when the page is not visible
document.title = "Don't go too far, hey...";
// 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";
// After another 2 seconds, revert to the original title
timeoutId = setTimeout(() => {
document.title = originalTitle;
}, 2000);
}
});
Technical Breakdown#
1. document.title
#
This is a simple yet powerful property that can be used to read or change the title content on the web page tab. We make the title "come alive" by dynamically assigning values.
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. It becomes true
when the user switches tabs or minimizes the browser; when the user returns, it changes back to false
.
3. visibilitychange
event#
This is the event triggered when the visibility of the page changes, making it very suitable for implementing this "detect user behavior" feature.
4. setTimeout
and clearTimeout
#
setTimeout
allows us to delay the title restoration operation for a few seconds when the user returns, making it feel more natural.clearTimeout
is used to ensure that there are no unnecessary delayed operations piling up, avoiding logical conflicts.
Features and Drawbacks#
-
Advantages:
- Simple implementation logic, intuitive code.
- Directly manages state through global variables, quickly completing functionality.
-
Drawbacks:
- Uses global variables
originalTitle
andtimeoutId
, which may conflict with other code. - Does not clean up event listeners, which may lead to potential memory leaks when the page unloads.
- Uses global variables
Improved Version: Suggestions from commenter liuzhen932#
liuzhen932 proposed a more modular version, encapsulating the code in an immediately invoked function and adding 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;
// Logic to handle visibility changes of the page
function handleVisibilityChange() {
// Clear the previous timer if it exists
clearTimeout(timeoutId);
if (document.hidden) {
// Set the title when the page is not visible
document.title = "Don't go too far, hey...";
} else {
// Set a prompt title when the page is visible
document.title = "Yay, you're back!ヾ(•ω•`)o";
// Restore the original title after a 2-second delay
timeoutId = setTimeout(() => {
document.title = originalTitle;
}, 2000);
}
}
// Cleanup logic before the page unloads
function beforeUnloadListener() {
// Remove the visibility change event listener to avoid memory leaks
document.removeEventListener("visibilitychange", handleVisibilityChange);
}
// Bind the visibility change event
document.addEventListener("visibilitychange", handleVisibilityChange);
// Remove related event listeners before the page unloads
window.addEventListener("beforeunload", beforeUnloadListener);
})();
Improvements#
- Modular Design:
- Uses an immediately invoked function to avoid global variable pollution.
- Event Cleanup:
- Removed the
visibilitychange
listener when the page unloads, reducing the risk of memory leaks.
- Removed the
- Conciseness:
- Utilizes ternary operators and logical short-circuiting to make the code more compact.
Where can it be used?#
I don't know, it's just interesting; it can be an Easter egg for your blog or a reminder for something, depending on how you use it!
Small Tips#
- Use Sparingly: Frequent title changes may annoy users, so control the trigger frequency.
- Compatibility Issues: Although modern browsers almost all support the Visibility API, it's best to handle compatibility if your user base uses older browsers.
I will continue to share codes like this in the future, feel free to use them, and if you can leave your blog in the comments, I wouldn't mind taking a look (
This article is synchronized and updated to xLog by Mix Space
The original link is https://ling.tblstudio.cn/posts/default/fun-with-js-dynamic-title