0

I´m not good at Javascript, but I am wondering how I can change the browser tab icon depending on tap color. I have found this script:

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

I am wondering how I could transfer this to; if darkmode yes:

<link rel="icon" href="dark"> 

If darkmode off:

<link rel="icon" href="light"> 

Keep in mind my JS knowledge is none existing, probably easy, but I didn't manage to find out. Help is greatly appreciated :)

andreasv
  • 450
  • 1
  • 4
  • 15

2 Answers2

1

Borrowing from this answer Changing website favicon dynamically

You could add this function to your JS

/*!
 * Dynamically changing favicons with JavaScript
 * Works in all A-grade browsers except Safari and Internet Explorer
 * Demo: http://mathiasbynens.be/demo/dynamic-favicons
 */

// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];

function changeFavicon(src) {
 var link = document.createElement('link'),
     oldLink = document.getElementById('dynamic-favicon');
 link.id = 'dynamic-favicon';
 link.rel = 'shortcut icon';
 link.href = src;
 if (oldLink) {
  document.head.removeChild(oldLink);
 }
 document.head.appendChild(link);
}

and then you can call this function only when dark mode is enabled like

if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    changeFavicon('http://www.google.com/favicon.ico');
}

If you wanted to simply add any element to the head in dark mode you could use mostly the same code

document.head = document.head || document.getElementsByTagName('head')[0];

if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    document.head.insertAdjacentHTML('beforeend', '<link rel="icon" href="dark">');
} else {
    document.head.insertAdjacentHTML('beforeend', '<link rel="icon" href="light">');
}
Brian Leishman
  • 8,155
  • 11
  • 57
  • 93
0

Depending of your CSS config I think it would be better to work with macro classes. In your body or site wrapper div you could set a class and change it accordingly with the mode.

Eg.:

<div id='site' class="dark"> 
   ...
</div>

OR

<div id='site' class="light"> 
   ...
</div>

Yours CSS should look like:

.light .title {}
.light .box {}
.light .header {}
.dark .title {}
.dark .box {}
.dark .header {}

The JS should look like:

function toggleMode(mode) {
   const siteWrapper = document.getElementById('site');
   siteWrapper.classList.remove('light','dark');   
   siteWrapper.classList.add(mode);
}