Created
March 20, 2022 05:49
-
-
Save giripriyadarshan/22c8dce03b97709c9882c6979fca7947 to your computer and use it in GitHub Desktop.
switch theme using javascript and css variables (https://blog.giripriyadarshan.com/blog/20220319-1/)
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
const darkThemeColors = new Map([ | |
['primary', '#68e0cf'], | |
['secondary', '#585d65'], | |
['text', '#edf8f4'], | |
['background', '#373b40'] | |
]); | |
const lightThemeColors = new Map([ | |
['primary', '#309485'], | |
['secondary', '#a7adcb'], | |
['text', '#1a1a1a'], | |
['background', '#d3d3d3'] | |
]); | |
async function toggleDarkMode() { | |
let rootVariables = document.querySelector(':root'); | |
let darkMode = document.getElementById("toggle"); | |
if (darkMode.checked) { // dark theme | |
for (let [key, value] of darkThemeColors.entries()) { | |
rootVariables.style.setProperty('--color-' + key, value); | |
} | |
} else { // light theme | |
for (let [key, value] of lightThemeColors.entries()) { | |
rootVariables.style.setProperty('--color-' + key, value); | |
} | |
} | |
return darkMode.checked; | |
} | |
window.onload = toggleDarkMode; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment