Search code examples
javascriptcssdarkmode

JS change browser tab icon when darkmode is enabled


I have this script, that works for what its supposed to:

const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  darkModeMediaQuery.addListener((e) => {
    const darkModeOn = e.matches;
    console.log(`Dark mode is ${darkModeOn ? '🌒 on' : '☀️ off'}.`);
  });

I (with my none existing JS knowledge) am trying to change the last line:

console.log(`Dark mode is ${darkModeOn ? '🌒 on' : '☀️ off'}.`);

to instead of showing it in the console.log change the browser tab icon. My idea (that I am yet to bring to life) is that:

if (dark-mode = on){ 
  $icon = "images/icon_dark.png";
}else{
  $icon = "images/icon_light.png";
  } 
}

then use the $icon in <link rel="icon" href="$icon">.
I know what I have written above is not how JS works, but it's just to illustrate what I want. I have seen other solutions, but I have found this idea to be the best for my intention.
Any help is greatly appreciated.


Solution

  • Yes, you don't need PHP here, but you can do it with JavaScript.

    Attach id to the element

    <link rel="icon" href="images/icon_light.png" id="favicon-icon">
    

    JS

    const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      darkModeMediaQuery.addListener((e) => {
        const darkModeOn = e.matches;
        console.log(`Dark mode is ${darkModeOn ? '🌒 on' : '☀️ off'}.`);
        document.getElementById("favicon-icon").href = darkModeOn ? 'images/icon_dark.png' : 'images/icon_light.png'
    });