The visibilitychange
event fires when the content of a tab becomes visible or hidden. This can happen when users switch tabs, minimize the browser, or move to a different application. In our case, we will use the visibilitychange event in JavaScript to create dynamic favicon switching.
The visibilitychange
event is part of the Page Visibility API, here’s what it detects:
- Tab switching: When a user moves to a different tab or back to your tab.
- Window minimizing: When the browser window is minimized or restored.
- Application switching: When a user switches to a different application or back to the browser.
- Mobile screen off: When a mobile device’s screen is turned off or on.
- Mobile app backgrounding: When a mobile browser app is sent to the background or brought to the foreground.
The Page Visibility API also includes the document.hidden
property, which you can use to check if a page is currently visible or hidden. We combine both to detect and respond to changes in page visibility, in this case, the favicon.
Implementing the dynamic favicon switching with visibilitychange:
const favicon = document.querySelector('link[rel="icon"]');
function updateFavicon() {
favicon.href = `favicon${document.hidden ? '-inactive' : ''}.ico`;
}
document.addEventListener("visibilitychange", updateFavicon);
updateFavicon();
// Even shorter you can go with just the below but I prefer separation of concern and readability as the above one:
document.addEventListener("visibilitychange", () => {
favicon.href = `favicon${document.hidden ? '-inactive' : ''}.ico`;
});
This script changes the favicon when the tab becomes inactive and reverts it when the tab is active again. Make sure that in your root folder or wherever you will put your favicons you have 2 favicons, the default one named favicon.ico for the inactive state (when the tab is hidden) and favicon-inactive.ico for the active state (when the tab is visible). If you need different naming, you can easily adjust the string in the updateFavicon
function.
Implementing favicon switching with the visibilitychange event is straightforward and effective and is supported in all modern browsers, you can play freely with it.
Why use this technique?
- Improved UX: Users can quickly identify which tab needs attention.
- Increased engagement: A changing favicon can draw users back to your site.
Tip: combine with other techniques
For a more versatile approach, consider combining this with:
- Title updates (e.g., “(1) New Message”).
- Browser notifications (with user permission).
- Sound notifications.
Learn more:
- Page Visibility API https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
- visibilitychange: https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event