Last active
July 21, 2023 14:31
-
-
Save hahuaz/01fcd1f428d451a4c4054fb8784c4669 to your computer and use it in GitHub Desktop.
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
<body> | |
<div class="ui-settings"> | |
<div> | |
<label for="dark">Enable dark mode:</label> | |
<input type="checkbox" name="dark" id="dark-mode-checkbox" /> | |
</div> | |
</div> | |
<div class="ui-elements"> | |
<div class="w-20 h-20 bg-green-500 dark:bg-gray-500"></div> | |
</div> | |
<script type="module"> | |
const DARK_MODE_CHECKBOX = document.getElementById( | |
'dark-mode-checkbox' | |
) as HTMLInputElement; | |
// On page load | |
if ( | |
localStorage['dark'] === 'true' || | |
(!('dark' in localStorage) && | |
window.matchMedia('(prefers-color-scheme: dark)').matches) | |
) { | |
document.documentElement.classList.add('dark'); | |
DARK_MODE_CHECKBOX.checked = true; | |
} else { | |
document.documentElement.classList.remove('dark'); | |
DARK_MODE_CHECKBOX.checked = false; | |
} | |
DARK_MODE_CHECKBOX.addEventListener('change', (e) => { | |
const { name, checked } = e.target as HTMLInputElement; | |
localStorage.setItem(name, checked.toString()); | |
document.documentElement.classList.toggle('dark'); | |
}); | |
</script> | |
</body> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment