DEV Community


Posted on • Updated on • Originally published at

Change page title dynamically ๐Ÿ”

Hello everyone,

This post is about changing the document title when the user leaves your site's tab.

A good way to grab the the user's attention is of course to write useful content ๐Ÿ˜
Being funny is also a very good strategy to keep users coming back to your blog.
A little bit of originality won't harm at all !

We are going to use the Page Visibility API to detect if the user is on your site's tab or on another tab, and change your site's tab title using the Document.title property and an awesome french song title ๐Ÿ˜‰

    // Grab the document title of your site's current tab.
    let currentTabTitle = document.title;
    // Listen to visibility change events
    document.addEventListener('visibilitychange', function () {
        // Fires when user leaves your site's tab.
        document.visibilityState === "hidden"
        // Document title when user leaves your site's tab.
        ? (document.title = `Ne Me Quitte Pas ๐Ÿ˜ญ`)
        // Document title when user comes back to your site's tab.
        : (document.title = currentTabTitle);
Enter fullscreen mode Exit fullscreen mode

This Conditional (ternary) operator is like an if...else statement

Important note: since the first change will occur when the user leaves your site's tab, we begin by listening to the hidden state (when the page's content is not visible to the user) and we change your tab title to whatever... Once the user gets back to your site's tab, the original tab title will be reassigned since we've grab it earlier.

You can see it in action on my own personal site where this small article was originally posted.

Don't forget to check out the song ๐ŸŽถ


Discussion (0)