Reputation: 125
I'm trying to implement a dark mode across my website which has 3 different pages. I made 3 separate javascript files to each page and copied the dark mode code to each one. Now I want to save the preference so that the user doesn't have to keep clicking the dark mode feature every single time they go to a different part of the site. This is what I have that changes it to dark mode. I've seen answers using localStorage but I'm still new to JS so I'm having trouble implementing it. Should I have only one javascript file for all 3 pages or keep it separate files?
<label class="switch">
<input type="checkbox" id="darkmode">
<span class="slider round"></span>
</label>
let checkbox = document.getElementById("darkmode");
let body = document.getElementById('body')
checkbox.addEventListener( 'change', function() {
if(this.checked) {
body.classList.add('dark')
} else {
body.classList.remove('dark')
}
});
Upvotes: 2
Views: 7079
Reputation:
A simple trick is to use the window.localstorage() or cookies(), this will help you to make this functionality easily.
For more information, you can see this article MDN Window.localStorage
& MDN cookies.Cookie
Practical example always help us 100%,
This is a better way to do this stuff.
https:// codepen.io/Md_Tahazzot/pen/xxKLmJa
Upvotes: 2
Reputation: 28414
In order to achieve this, you can do the following:
checkbox.addEventListener( 'change', function() {
localStorage.setItem('dark',this.checked);
if(this.checked) {
body.classList.add('dark')
} else {
body.classList.remove('dark')
}
});
if(localStorage.getItem('dark')) {
body.classList.add('dark');
}
Upvotes: 1