banner
wling

wling

bilibili

Add some fun to your blog: Change the webpage title with JS

Recently, I wrote a very cool piece of JavaScript code, and I tried it on my blog. The effect is amazing!
If your blog supports custom JS, you can try it too, making the 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; and when users return 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 it 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 changes in page visibility
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 webpage tab. We make the title "come alive" through dynamic assignment.

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 event is triggered when the page visibility changes, making it perfect 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 ensures that no unnecessary delayed operations accumulate, avoiding logical conflicts.

Features and Drawbacks#

  • Advantages:

    • The implementation logic is simple, and the code is intuitive.
    • Directly manages state through global variables, quickly completing the functionality.
  • Drawbacks:

    • Uses global variables originalTitle and timeoutId, which may conflict with other code.
    • Does not clean up event listeners, which may lead to potential memory leaks when the page is unloaded.

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 is 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 page visibility changes
  function handleVisibilityChange() {
    // Clear any previous timer
    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:
    • Removes the visibilitychange listener when the page unloads, reducing the risk of memory leaks.
  • Conciseness:
    • Uses ternary operators and logical short-circuiting to make the code more compact.

Where can it be used in practice?#

I don't know, it's just interesting! This could 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 such code in the future, feel free to use it. If you can leave your blog in the comments, I wouldn't mind checking it out!

This article is synchronized and updated to xLog by Mix Space. The original link is https://ling.crashvibe.cn/posts/default/fun-with-js-dynamic-title

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.