Change page title dynamically

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)

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 wright here, change to another tab or open a new one 😉

Don't forget to check out the song 🎶