-
Notifications
You must be signed in to change notification settings - Fork 0
/
dark-mode-switch.js
47 lines (43 loc) · 1.49 KB
/
dark-mode-switch.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const darkSwitch = document.getElementById('darkSwitch');
window.addEventListener('load', () => {
if (darkSwitch) {
initTheme();
darkSwitch.addEventListener('change', () => {
resetTheme();
});
}
});
/**
* Summary: function that adds or removes the attribute 'data-theme' depending if
* the switch is 'on' or 'off'.
*
* Description: initTheme is a function that uses localStorage from JavaScript DOM,
* to store the value of the HTML switch. If the switch was already switched to
* 'on' it will set an HTML attribute to the body named: 'data-theme' to a 'dark'
* value. If it is the first time opening the page, or if the switch was off the
* 'data-theme' attribute will not be set.
* @return {void}
*/
function initTheme() {
const darkThemeSelected =
localStorage.getItem('darkSwitch') !== null &&
localStorage.getItem('darkSwitch') === 'dark';
darkSwitch.checked = darkThemeSelected;
darkThemeSelected ? document.body.setAttribute('data-theme', 'dark') :
document.body.removeAttribute('data-theme');
}
/**
* Summary: resetTheme checks if the switch is 'on' or 'off' and if it is toggled
* on it will set the HTML attribute 'data-theme' to dark so the dark-theme CSS is
* applied.
* @return {void}
*/
function resetTheme() {
if (darkSwitch.checked) {
document.body.setAttribute('data-theme', 'dark');
localStorage.setItem('darkSwitch', 'dark');
} else {
document.body.removeAttribute('data-theme');
localStorage.removeItem('darkSwitch');
}
}