Search code examples
javascriptjqueryonfocus

JQuery set browser title on blur to be working widthout focus


Good day,

With the help of a piece of code found on stackoverflow I managed to piece together my own version of the on blur title change script.

The only problem I am facing is when I am loading the page and I do not click anywhere on the page itself {hence I do not 'focus'} the script does not work.

I added a piece of code where I duplicated the focus method and changed it to load.

$(function () {
    var message = '( ! ) :+Do not forget your reservation+:';
    var original = $('title').text();

    $(window).load(function () {
        console.log('window focussed');
        if (original) {
            document.title = original;
        }
    }).focus(function () {
        console.log('window focussed');
        if (original) {
            document.title = original;
        }
    }).blur(function () {
        console.log('window blurred');
        var title = $('title').text();
        if (title != message) {
            original = title;
        }
        document.title = message;
    });
    console.log('current title : ' + original);
});

However this does not resolve my issue totally. At this point I need click on another tab, go back and again click on another tab. So this is pretty pointless.

What am I missing to make this script work right from the start?


solution Many thanks to : @Brian

Adding a trailing focus(); did the trick. (And not the one from Ford.. which is great but does not work here)


Solution

  • Add a .focus() call to the end of the chain to force a focus event on load:

    $(function () {
        var message = '( ! ) :+Do not forget your reservation+:';
        var original = $('title').text();
    
        $(window).load(function () {
            console.log('window focussed');
            if (original) {
                document.title = original;
            }
        })
        .focus(function () {
            console.log('window focussed');
            if (original) {
                document.title = original;
            }
        })
        .blur(function () {
            console.log('window blurred');
            var title = $('title').text();
            if (title != message) {
                original = title;
            }
            document.title = message;
        })
        .focus(); // add this line
        console.log('current title : ' + original);
    });