Question

I'm trying to run a bit of code to flash the favicon back and forth between 2 .ico's indefinitely every second. So far I've got this code which changes it once, but not again;

var favUrl = "favicon.ico";
var flashFavIco = function() {
    if(favUrl == "favicon.ico") {
        favUrl = "favicon-white.ico";
    } else {
        favUrl = "favicon.ico";
    }
    console.log(favUrl);
    var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.mysite.com/' + favUrl;
    document.getElementsByTagName('head')[0].appendChild(link);
};
setInterval(flashFavIco, 1000);

I tested adding console.log()s in the if/else sections to check that favURL was being set each second, which it was indeed. So I'm a little stuck as to why the favicon only changes once. Is this a browser issue?

Edit: I do realise this continually adds new <link ... tags to the head, and I'm working on writing that appendChild part differently, this does not affect my original question

Was it helpful?

Solution

I re-wrote part of it and now have it working;

var favUrl = "favicon.ico";
var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.mysite.com/' + favUrl;
    link.id = "favico";
document.getElementsByTagName('head')[0].appendChild(link);

var flashFavIco = function() {
    if(favUrl == "favicon.ico") {
        favUrl = "favicon-white.ico";
    } else {
        favUrl = "favicon.ico";
    }
    $('#favico').prop('href', 'http://www.mysite.com/' + favUrl);
};
setInterval(flashFavIco, 1000);

OTHER TIPS

Rewrote it for you.

// Edit these
var faviconNormal = "/faviconNormal.ico";
var faviconActive = "/faviconActive.ico";
var faviconID = "#myfavicon"; // CSS selector for your <link> element

// Declarations
var faviconElement = document.querySelector(faviconID);
var faviconIsActive = false;

function flashFavicon() {
    if (faviconIsActive == false) {
        changeFavicon(faviconActive);
        faviconIsActive = true;
    }
    else {
        changeFavicon(faviconNormal);
        faviconIsActive = false;
    }
}

function changeFavicon(src) {
    faviconElement.href = src;
}

// Run
var initFlashing = setInterval(flashFavicon, 1000);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top