Changing tab title on focus loss or switch

Many of you have been asking me how to change tab’s title when you navigate to a different page. Why would you want to do this? Other than to add a little bit of user engagement there isn’t. So what’s the result? Just open another browser tab and focus on it. You will see that this tab’s title changes to “Miss you 🙁 “ . It’s a little subtle user experience hack. When first implemented as a test we didn’t think anyone would notice it. Yet just like any small detail, that’s what people notice most. Anyway, here is how to do it.

Overview

We will create a small Java Script snippet that we can add to our document ready function. This snippet will listen for visibility changes of the window. If it detects a change we will set a variable to hidden and update our tab title. We will continue to monitor for changes and once it changes back we will revert the change. Each browser handles the state changes differently so then we will have to cover all our cases. This also uses Jquery which most sites use these days.

Step 1: Basic setup

You can either create a new javascript file or add it to a document ready function that you might already have. This is probably going to be the case for most people. Create a new file called fun-tabs.js and place it in your js folder (you can make one if you don’t have it). Then we are going to load it at the bottom of your HTML before the </body> tag like this:

<script type='text/javascript' src='http://example.com/js/fun-tabs.js'></script> 

If you are building a WordPress site it’s better to enqueue a script in your theme’s functions.php file, this way WordPress will handle all the loading and dependency for you. So open your functions.php theme file and add this to the end of it.

//load our custom js only if we are not in admin
if ( ! is_admin() ) {
	wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri(). ' /js/fun-tabs.js', array(‘jquery’), '1.0.0', true );
}

You can update the path and the name to whatever suits you. The true in the end of our function is to let WordPress know that we want our script to be loaded at the bottom of HTML and having ‘jquery’ in our array tells WordPress to load our script after jquery.

 

Step 2: Adding our script

Now that we have the file created and enqueued, open it in your favorite editor such as Php Storm / Sublime and add this:

jQuery(document).ready(function($) {

(function() {
        var hidden = "hidden";
        var oldtitle = document.title;
        var currenttitle;

        // Standards based on browsers:
        if (hidden in document)
            document.addEventListener("visibilitychange", onchange);
        else if ((hidden = "mozHidden") in document)
            document.addEventListener("mozvisibilitychange", onchange);
        else if ((hidden = "webkitHidden") in document)
            document.addEventListener("webkitvisibilitychange", onchange);
        else if ((hidden = "msHidden") in document)
            document.addEventListener("msvisibilitychange", onchange);
        // IE 9 and lower:
        else if ("onfocusin" in document)
            document.onfocusin = document.onfocusout = onchange;
        // All others:
        else
            window.onpageshow = window.onpagehide
                = window.onfocus = window.onblur = onchange;

       //if tab change happens set status to either hidden or visible
        function onchange (evt) {
            var v = "visible", h = "hidden",
                evtMap = {   //check events and set status based on event type
                    focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
                };

            evt = evt || window.event;
            if (evt.type in evtMap) {  // check the title
                currenttitle = oldtitle;
                $(document).attr('title', currenttitle);
            }
            else { // We are in hidden state so create unique title
                currenttitle = this[hidden] ? "I have changed " : oldtitle; //update to whatever you want
                $(document).attr('title', currenttitle);
            }

        }

        // set the initial state (but only if browser supports the Page Visibility API)
        if( document[hidden] !== undefined )
            onchange({type: document[hidden] ? "blur" : "focus"});
    })();
});

Of course, if you already got the Document Ready function in another js file you can just add our script into yours and save the whole new file creation and enqueue process. You can also just paste the whole thing inline into your HTML as long as you declare that it’s a script beforehand and have Jquery loaded. Here is such HTML file for your download pleasure.

 

Where it says “I have changed” you can add your own text. You can also add your own logic in that step. For example, have text only change if you are on a certain page or adding a delay so the text doesn’t show right away.

Other uses

You should now be all set. The great thing about this is that because it’s just java script it doesn’t affect SEO. You can also use Emoji icons as in your text  (since almost everything support them). I would still not abuse this. In the end, the tab’s job is to let the user know what page it represents so I wouldn’t use on a big blog site.

Got other creative uses for it? Let me know how you ended up using this.

Leave a Reply