Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Change favicon on switching browser tabs in JavaScript

I was browsing through my Twitter feed and I saw something pretty subtle yet mind-blowing. One of the guys from the Astro team was showing off some of the new things they have done for their brand redesign.

One of the things that caught my attention was the favicon that changes when you switch between browser tabs.

Essentially, the favicon changes to a grayscale version of the original favicon when the tab is inactive and changes back to the original favicon when the tab is active.

It looked pretty cool!

They have even shared how they did it. So, I decided to try it on my Notepad app. Here’s how it looks like.

Change favicon on switching browser tabs in JavaScript

Pretty sick, no?

Here’s the code that does this magic.

const favicon = document.querySelector('link[rel="icon"]')

document.addEventListener("visibilitychange", () => {
    const hidden = document.hidden

    favicon.setAttribute(
        "href", 
        `/favicon${hidden ? "-hidden" : ""}.ico`
    )
})

As you can tell, first, we grab the instance of the favicon by using the querySelector() method. And then the visibilitychange event is used to detect when the content of the tab is hidden or visible. And based on that, we can manipulate the favicon.

For this to work, all I did is create a favicon-hidden.ico file (which is a grayscale version of the original favicon). And then, changed the href attribute of the link element to the favicon-hidden.ico file using the setAttribute() method when the tab is hidden. And switched back to the original favicon when the tab is visible.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?