Created
April 5, 2022 17:20
-
-
Save diggeddy/b1f43a3f29fecfbb1fb0c6ad613b7b76 to your computer and use it in GitHub Desktop.
DarkMode Script
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
(function() { | |
var dmtoggle = document.getElementById('dmtoggle'); | |
var body = document.body; | |
var darkMode = function() { body.classList.add('dark-mode'); } | |
var lightMode = function() { body.classList.remove('dark-mode'); } | |
var systemPref = undefined; | |
var localPrefDark = function() { | |
if (systemPref == 'dark') localStorage.setItem('pref-scheme', 'system'); | |
else localStorage.setItem('pref-scheme', 'dark'); | |
setByLocalOrSystem(); | |
} | |
var localPrefLight = function() { | |
if (systemPref == 'light') localStorage.setItem('pref-scheme', 'system'); | |
else localStorage.setItem('pref-scheme', 'light'); | |
setByLocalOrSystem(); | |
} | |
var systemPrefDark = function() { systemPref = 'dark'; setByLocalOrSystem(); } | |
var systemPrefLight = function() { systemPref = 'light'; setByLocalOrSystem(); } | |
var setByLocalOrSystem = function() { | |
let localPref = localStorage.getItem('pref-scheme'); | |
if (localPref && localPref !== 'system') { | |
if (localPref == 'dark') darkMode(); | |
if (localPref == 'light') lightMode(); | |
} | |
else if (systemPref) { | |
if (systemPref == 'dark') darkMode(); | |
if (systemPref == 'light') lightMode(); | |
} | |
} | |
dmtoggle.addEventListener('click', function() { | |
if (body.classList.contains('dark-mode')) localPrefLight(); | |
else localPrefDark(); | |
}); | |
if (window.matchMedia) { | |
if (window.matchMedia('(prefers-color-scheme: dark)').matches) systemPrefDark(); | |
window.matchMedia('(prefers-color-scheme: dark)').addListener(function(q) { if (q.matches) systemPrefDark(); }); | |
if (window.matchMedia('(prefers-color-scheme: light)').matches) systemPrefLight(); | |
window.matchMedia('(prefers-color-scheme: light)').addListener(function(q) { if (q.matches) systemPrefLight(); }); | |
} | |
setByLocalOrSystem(); | |
setTimeout(function() { body.classList.add('dark-mode-animate')}, 100); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment