#AD "Ten++ Ways to Make Money as a Developer" eBook by Florin Pop
#js

Change a website favicon dynamically using JavaScript

Last modified February 9th 2021 | GitHub Source Code [GitHub]

Today we’ll be using JavaScript to change a website favicon dynamically. There are a number of reasons for wanting to do this but for the purposes of this tutorial we’ll be creating a script that changes the favicon on certain days of the year.

First thing we need to do is get the current month and day:

const [month, day] = new Date().toLocaleDateString("en-US").split("/");
Code language: JavaScript (javascript)

This returns a 2-4 digit string containing the month and day which we’ll use to check against a series of predefined dates using the same date format:

let favicon; switch (month + day) { case "214": favicon = "💕"; break; case "1031": favicon = "🎃"; break; case "1225": favicon = "🎅🏼"; break; default: favicon = "🌐"; }
Code language: JavaScript (javascript)

The dates used are Valentines Day (Feb 14th), Halloween (Oct 31st), and Christmas (Dec 25th). If the current date doesn’t match any of these it’ll fall back to a default favicon.

Now we just need to insert the favicon into the <head> of the document:

const dynamicFavicon = (favicon) => { const link = document.createElement("link"); link.rel = "shortcut icon"; link.type = "image/svg+xml"; link.href = "data:image/svg+xml, <svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22> <text y=%22.9em%22 font-size=%2290%22>" + favicon + "</text></svg>"; document.head.appendChild(link); }; dynamicFavicon(favicon);
Code language: JavaScript (javascript)

As we’re using emojis for the favicon they must be within a SVG <text> element to render correctly. You can test each of the different favicon’s by switching out the holiday date with the current date. More emojis can be found at Emojipedia.

Related Posts