Last active
February 28, 2020 23:17
-
-
Save jouni-kantola/a94ee08ea61fc9c989c4718ef5e4afe2 to your computer and use it in GitHub Desktop.
Dark & light mode switch (with preferred choice kept in localStorage)
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<style> | |
:root { | |
--light-color: #fafafa; | |
--dark-color: #222; | |
--background-color: var(--light-color); | |
--text-color: var(--dark-color); | |
} | |
html, | |
body { | |
padding: 0; | |
margin: 0; | |
font-family: Helvetica, Arial, sans-serif; | |
font-weight: 100; | |
} | |
html { | |
height: 100%; | |
} | |
body { | |
min-height: 100%; | |
} | |
input[name='color-scheme'], | |
input[name='color-scheme']:checked+label { | |
display: none; | |
} | |
#dark-mode:checked~label, | |
#dark-mode:checked~.page { | |
--background-color: var(--dark-color); | |
--text-color: var(--light-color); | |
} | |
.page { | |
display: flex; | |
align-items: center; | |
justify-content: center; | |
min-height: 100vh; | |
font-size: 3rem; | |
background-color: var(--background-color); | |
color: var(--text-color); | |
} | |
.color-scheme { | |
position: absolute; | |
top: 1rem; | |
right: 1rem; | |
width: 4rem; | |
font-size: 3rem; | |
line-height: 4rem; | |
text-align: center; | |
user-select: none; | |
color: var(--text-color); | |
} | |
</style> | |
<script> | |
const colorScheme = localStorage.getItem("color-scheme") || colorScheme; | |
</script> | |
</head> | |
<body> | |
<input type="radio" id="dark-mode" value="dark-mode" name="color-scheme"> | |
<label for="dark-mode" class="color-scheme">☾</label> | |
<!-- checked; default to light mode if JavaScript disabled --> | |
<input type="radio" id="light-mode" value="light-mode" name="color-scheme" checked> | |
<label for="light-mode" class="color-scheme">☀︎</label> | |
<script> | |
// use preferred color scheme | |
document.getElementById("light-mode").checked = colorScheme === "light-mode"; | |
document.getElementById("dark-mode").checked = colorScheme === "dark-mode"; | |
</script> | |
<div class="page"> | |
<p class="content">Hello world!</p> | |
</div> | |
<script> | |
Array.from(document.querySelectorAll("input[name='color-scheme']")) | |
.forEach(el => el.addEventListener("click", event => { | |
localStorage.setItem("color-scheme", event.target.id); | |
})); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment