DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at w3collective.com

9 2

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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay