Things you'll need:
- Font Awesome
- Minimal CSS knowledge for very specific changes to your site
- To choose your on off icon's! I chose to use
fa-sun
and fa-moon
- check it out in the side nav bar.
Check out a minimal demo on jsfiddle
Javscript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
const darkSwitch = document.getElementById("darkSwitch");
const toggle = document.getElementById("darkSwitchToggle")
const dm_off = "fa-sun"
const dm_on = "fa-moon"
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()
}))
});
|
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
:root {
--dark-mode-dark: #345;
--dark-mode-light: #f0f8ff;
}
[data-theme="dark"] .main {
background-color: var(--dark-mode-dark) !important;
color: var(--dark-mode-light) !important;
}
/* Add this class to images you want to invert! */
[data-theme="dark"] .invertable {
filter: invert(1);
}
#darkSwitch {
position: relative;
}
|
HTML
1
2
3
4
5
6
|
<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>
|