Add some fun to your blog: Change the page title with JS
Recently, I wrote a really cool piece of JavaScript code. I tried it on my blog, and the effect was amazing!
If your blog supports custom JS, you can also try it to make the page 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 go too far..." to "retain" the user; when the user returns to the page, the title enthusiastically displays "Yay, you're back! ヾ (•ω•`)o", and after two seconds it automatically reverts to the original title.
Isn't that cool? Here's the code!
// 定义原始标题
const originalTitle = document.title;
let timeoutId; // 用于存储延时器 ID
// 监听页面的可见性变化
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
// 当页面不可见时更改标题
document.title = "别走太远了啊喂...";
// 清除可能存在的延时器
clearTimeout(timeoutId);
} else {
// 当页面可见时,延迟 2 秒更改标题
document.title = "好耶,回来啦!ヾ (•ω•`)o";
// 再过 2 秒恢复到原始标题
timeoutId = setTimeout(() => {
document.title = originalTitle;
}, 2000);
}
});
Technical Breakdown
1. document.title
This is a simple yet powerful property that can read or change the title content of the web page 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 hidden. When the user switches to another tab or minimizes the browser, it becomes true; when the user returns, it becomes false again.
3. visibilitychange event
This event is triggered when the page visibility changes, making it very suitable for implementing such "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 more natural.clearTimeoutensures that no redundant delayed operations accumulate, avoiding logic conflicts.
Features and limitations
Advantages:
- Simple implementation logic, intuitive code.
- Directly manages state through global variables, quickly completing the functionality.
Disadvantages:
- Uses global variables
originalTitleandtimeoutId, which may conflict with other code. - Does not clean up event listeners, potentially causing 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 and adds an event cleanup mechanism. Here is the improved code:
(function () {
"use strict";
// 保存原始标题,用于后续恢复
const originalTitle = document.title;
// 存储定时器 ID,防止多个定时器冲突
let timeoutId;
// 处理页面可见性变化的逻辑
function handleVisibilityChange() {
// 清除上一次可能存在的延时器
clearTimeout(timeoutId);
if (document.hidden) {
// 当页面不可见时,设置标题
document.title = "别走太远了啊喂...";
} else {
// 当页面可见时,先设置一个提示标题
document.title = "好耶,回来啦!ヾ(•ω•`)o";
// 延时 2 秒后恢复原始标题
timeoutId = setTimeout(() => {
document.title = originalTitle;
}, 2000);
}
}
// 页面即将卸载时的清理逻辑
function beforeUnloadListener() {
// 移除可见性变化的事件监听器,避免内存泄漏
document.removeEventListener("visibilitychange", handleVisibilityChange);
}
// 绑定页面可见性变化的事件
document.addEventListener("visibilitychange", handleVisibilityChange);
// 在页面卸载之前移除相关事件监听器
window.addEventListener("beforeunload", beforeUnloadListener);
})();
Improvements
- Modular design:
- Uses an immediately invoked function expression to avoid polluting global variables.
- Event cleanup:
- Removes the
visibilitychangelistener when the page is unloaded, reducing memory leak risks.
- 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 can be an Easter egg for your blog, or a reminder, depending on your needs!
Small tips
- Use moderately: Frequent title changes can be annoying, so control the trigger frequency.
- Compatibility issues: Although modern browsers almost all support the Visibility API, if your users are on older browsers, it's best to handle compatibility.
I will continue to share code like this in the future. Feel free to use it however you like, and if you can leave your blog in the comments, it's not impossible for me to go and check it out. (