iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎨

Let's Change Favicon Colors Dynamically!

に公開

Examples of switching between light mode and dark mode

For example, GitHub changes its Favicon color depending on whether you are viewing it in light mode or dark mode.

Examples of switching per page

On the manga site SHURO, the Favicon color changes (likely) depending on the work.

For example, in "そうです、私が美容バカです。", the Favicon is light blue.

And in "恋とか夢とかてんてんてん", it becomes a green Favicon.

Let's change the Favicon color!

As you can see, it looks cool when the Favicon color changes, so let's try changing it.

While there might be a way to dynamically swap .ico files using JavaScript, I'll take this opportunity to use SVG Favicons.
Safari still doesn't support SVG Favicons, though...

https://caniuse.com/link-icon-svg

Preparing the SVG Favicon

To start with, let's prepare a simple circular SVG.

<svg version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
  <circle cx="8" cy="8" r="8" fill="#000000" />
</svg>

By Base64 encoding this and writing HTML like the following, the SVG becomes the Favicon.

    <link
      rel="icon"
      href="data:image/svg+xml;base64,PHN{略}Zz4="
      sizes="any"
      type="image/svg+xml"
    />

At this point, it's just a solid black circle as the Favicon, which isn't very exciting, so I want to change the color.

How to change the color

Since we're at it, let's make the color change based on the time of access using OKLCH.

Basically, all you need to do is change the fill of the circle.

css

:root {
  --hue: 235;
  --accent-color: oklch(37% 0.16 var(--hue));
}

js

  const date = new Date();
  const seconds =
    date.getSeconds() + 60 * date.getMinutes() + 60 * 60 * date.getHours();
  const hue = (Math.round(seconds / 240) + 235).toString();
  document.documentElement.style.setProperty("--hue", hue);

  window.onload = () => {
    const faviconSvg = `<svg version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"><circle cx="8" cy="8" r="8" fill="${window.getComputedStyle(document.documentElement).getPropertyValue("--accent-color")}" /></svg>`;
    const linkSvgFavicon = document.querySelector(
      "link[rel='icon'][type='image/svg+xml']",
    );
    linkSvgFavicon?.setAttribute(
      "href",
      `data:image/svg+xml;base64,${btoa(faviconSvg)}`,
    );
  };

Results

At the time of writing, I have implemented this on my own site.

https://studio15.jp/

When I accessed it around 8 PM, the Favicon was green.

If you access it around midnight, it should become a blue Favicon.

See also

https://hail2u.net/blog/mozoushi.html

Discussion