I’ve dark mode enabled on the website. It currently has a toggle switch, which changes the layout from light to dark and vice versa.
It is using the following code:
JavaScript
x
19
19
1
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
2
const currentTheme = localStorage.getItem('theme');
3
if (currentTheme) {
4
document.documentElement.setAttribute('data-theme', currentTheme);
5
if (currentTheme === 'dark') {
6
toggleSwitch.checked = true;
7
}
8
}
9
10
function switchTheme(e) {
11
if (e.target.checked) {
12
document.documentElement.setAttribute('data-theme', 'dark');
13
localStorage.setItem('theme', 'dark');
14
} else {
15
document.documentElement.setAttribute('data-theme', 'light');
16
localStorage.setItem('theme', 'light');
17
}
18
}
19
toggleSwitch.addEventListener('change', switchTheme, false);
JavaScript
1
8
1
<div class="theme-switch-wrapper">
2
<label class="theme-switch" for="checkbox">
3
<input type="checkbox" id="checkbox"/>
4
<div class="slider round"></div>
5
</label>
6
<em>DARK</em>
7
<strong>MODE</strong>
8
</div>
Now I want to upgrade to an icon click. For example, if there is light mode enabled, the icon for dark mode should be seen upon clicking it, the user will get dark mode on. Same, if dark mode is enabled, the icon for the light mode to be displayed, and if the user clicks it, the light mode is activated.
Thanks for any help or suggestions.
Advertisement
Answer
in the HTMl make a new image as a lable:
JavaScript
1
6
1
<label class="theme-switch" for="checkbox">
2
<img width="30" id="switcher" src="">
3
<input type="checkbox" id="checkbox" />
4
<div class="slider round"></div>
5
</label>
6
then you can use the set attribute to switch the source
JavaScript
1
27
27
1
<script>
2
const switcher = document.querySelector("#switcher");
3
switcher.setAttribute('src', 'https://vectorified.com/images/switch-button-icon-19.png');
4
5
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
6
const currentTheme = localStorage.getItem('theme');
7
if (currentTheme) {
8
document.documentElement.setAttribute('data-theme', currentTheme);
9
if (currentTheme === 'dark') {
10
toggleSwitch.checked = true;
11
}
12
}
13
14
function switchTheme(e) {
15
if (e.target.checked) {
16
document.documentElement.setAttribute('data-theme', 'dark');
17
localStorage.setItem('theme', 'dark');
18
switcher.setAttribute('src', 'https://vectorified.com/images/switch-button-icon-19.png');
19
} else {
20
document.documentElement.setAttribute('data-theme', 'light');
21
localStorage.setItem('theme', 'light');
22
switcher.setAttribute('src', 'https://image.flaticon.com/icons/png/512/37/37474.png');
23
}
24
}
25
toggleSwitch.addEventListener('change', switchTheme, false);
26
</script>
27