Last active
September 18, 2020 23:19
-
-
Save Bobz-zg/77a31bb684047b8ec62bb5faa25f0303 to your computer and use it in GitHub Desktop.
Dark mode favicon
This file contains 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
/** | |
* HTML Markup to place in your <head> tag | |
* <link rel="icon" type="image/png" href="/favicon.png" data-dark="/favicon-dark.png" /> | |
*/ | |
// Attach listener to DOM Loaded | |
window.addEventListener( 'DOMContentLoaded', setFavicon ); | |
// Set specific favicon if browser is in dark mode | |
function setFavicon() { | |
if ( window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ) | |
{ | |
const favicon = document.querySelector('[data-dark]'); | |
// No icon found | |
if ( ! favicon ) | |
{ | |
return; | |
} | |
// Dark version available | |
if ( favicon.dataset.dark ) | |
{ | |
favicon.href = favicon.dataset.dark; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment