Search code examples
htmlcssbrowserfavicon

How can I change my favicon dynamically depending on the state of the browser tab?


Thanks for looking. In most browsers, my favicon has high contrast (looks good) when the tab is selected but low contrast (hard to see) when the tab is not selected.

Is there some sort of "hook" common to most browsers that can tell me when my page is not the active tab so that I can switch for a higher contrast favicon and then switch back to the regular one when the tab is active?


Solution

  • To do this you would use the window's focus and blur events.

    $(window).focus(function() {
        var link = document.createElement('link');
        link.type = 'image/x-icon';
        link.rel = 'shortcut icon';
        link.href = 'http://www.stackoverflow.com/favicon.ico';
        document.getElementsByTagName('head')[0].appendChild(link);
    });
    
    $(window).blur(function() {
        var link = document.createElement('link');
        link.type = 'image/x-icon';
        link.rel = 'shortcut icon';
        link.href = 'http://www.stackoverflow.com/favicon.ico';
        document.getElementsByTagName('head')[0].appendChild(link);
    });
    

    Or with even shorter and the following HTML for favicon

    <link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />
    

    $(window).focus(function() {
        $("#favicon").attr("href","favicon1.png");
    });
    
    $(window).blur(function() {
        $("#favicon").attr("href","favicon2.png");
    });