javascript
January 17, 2021
Toggle Dark Mode with Javascript & Local Storage
index.html
<!DOCTYPE html>
<html
lang="en">
<head>
<meta charset="UTF-8" />
<title></title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<script>
var app = document.getElementsByTagName("BODY")[0];
if (localStorage.lightMode == "dark") {
app.setAttribute("data-light-mode", "dark");
}
</script>
<h1>
Toggle Dark Mode with <br />
Javascript & Local Storage
</h1>
<button onclick="toggle_light_mode()">
Toggle Light Mode
</button>
<script src="./script.js"></script>
</body>
</html>
script.js
function toggle_light_mode() {
var app = document.getElementsByTagName("BODY")[0];
if (localStorage.lightMode == "dark") {
localStorage.lightMode = "light";
app.setAttribute("data-light-mode", "light");
} else {
localStorage.lightMode = "dark";
app.setAttribute("data-light-mode", "dark");
}
console.log("lightMode = " + localStorage.lightMode);
}
style.css
body {
transition: background-color 0.3s;
text-align: center;
font-family: sans-serif;
padding-top: 3em;
}
h1 {
font-weight: normal;
}
button {
padding: 1em;
font-size: 1em;
background: #000;
color: #fff;
border: none;
cursor: pointer;
transition: .3s;
}
button:hover {
opacity:.5;
}
body[data-light-mode="dark"] {
background-color: #000;
color: #eee;
}
body[data-light-mode="dark"] button {
background-color: #fff;
color: #000;
}