Created
June 3, 2021 19:10
-
-
Save eclarrrk/821b06939998940a2a33ef1c21fa5f7f to your computer and use it in GitHub Desktop.
Show a different favicon depending on the browser color scheme — light mode or dark mode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- From https://glitch.com/edit/#!/zesty-soybean?path=script.js%3A31%3A0 --> | |
<link rel="icon" href="<?php echo get_stylesheet_directory_uri(); ?>/path/to/favicon-light.png" | |
id="light-scheme-icon"> | |
<link rel="icon" href="<?php echo get_stylesheet_directory_uri(); ?>/path/to/favicon-dark.png" | |
id="dark-scheme-icon"> | |
<script> | |
function setupIcons() { | |
const lightSchemeIcon = document.querySelector('link#light-scheme-icon'); | |
const darkSchemeIcon = document.querySelector('link#dark-scheme-icon'); | |
function setLight() { | |
document.head.append(lightSchemeIcon); | |
darkSchemeIcon.remove(); | |
} | |
function setDark() { | |
lightSchemeIcon.remove(); | |
document.head.append(darkSchemeIcon); | |
} | |
const matcher = window.matchMedia('(prefers-color-scheme:dark)'); | |
function onUpdate() { | |
if (matcher.matches) { | |
setDark(); | |
} else { | |
setLight(); | |
} | |
} | |
matcher.addListener(onUpdate); | |
onUpdate(); | |
} | |
setupIcons(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment