Change a website favicon dynamically using JavaScript

michaelburrows

Michael Burrows

Posted on February 8, 2021

Change a website favicon dynamically using JavaScript

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("/");
Enter fullscreen mode Exit fullscreen mode

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 = "🌐";
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
michaelburrows
Michael Burrows

Posted on February 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related