JSFiddle - React, Tailwind, and code Playground
by Andy Challis
HTML
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.14.0/css/all.css">
<!DOCTYPE html>
<html>
<body>
<div class="main">
<div id="darkSwitch">
<span class="fa-stack fa-1x">
<i class="fas fa-circle fa-stack-2x"></i>
<i id="darkSwitchToggle" class="fa fa-stack-1x fa-inverse"></i>
</span>
</div>
</div>
</body>
</html>
CSS
:root {
--dark-mode-dark: #345;
--dark-mode-light: #f0f8ff;
}
.main {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
[data-theme="dark"] .main {
background-color: var(--dark-mode-dark) !important;
color: var(--dark-mode-light) !important;
}
[data-theme="dark"] .fa-inverse {
color: var(--dark-mode-dark) !important;
}
/* Add this class to images you want to invert! */
[data-theme="dark"] .invertable {
filter: invert(1);
}
#darkSwitch {
position: relative;
}
JavaScript
// Set these to anything you like from font awesome!
const dm_off = "fa-sun"
const dm_on = "fa-moon"
document.addEventListener('DOMContentLoaded', function() {
const darkSwitch = document.getElementById("darkSwitch");
const toggle = document.getElementById("darkSwitchToggle")
function initTheme() {
const e = null !== localStorage.getItem("darkSwitch") && "dark" === localStorage.getItem("darkSwitch");
if (e) {
toggle.classList.add(dm_on)
document.body.setAttribute("data-theme", "dark")
} else {
toggle.classList.add(dm_off)
document.body.removeAttribute("data-theme")
}
}
function resetTheme() {
if (toggle.classList.contains(dm_off)) {
document.body.setAttribute("data-theme", "dark")
localStorage.setItem("darkSwitch", "dark")
} else {
document.body.removeAttribute("data-theme")
localStorage.removeItem("darkSwitch")
}
toggle.classList.toggle(dm_off)
toggle.classList.toggle(dm_on)
}
window.addEventListener("load", () => {
darkSwitch && (initTheme(), darkSwitch.addEventListener("click", () => {
resetTheme()
}))
});
})