Reputation: 83
On my Blogger blog, I am trying to create a dark mode light mode toggler. I have successfully created the toggler, but now I want to save the user preference so that if a user left with dark mode, he/she will get dark mode when he/she will get dark mode only after returning.
This is the code I have written so far. I need help with the local storage/ cookie thing to save user preference.
<b:tag aria-label='Dark Mode' class='darkmode-toggle' id='modetog' name='a' onclick='myFunction()'><i class='fas fa-adjust'/></b:tag>
<script>
/* Dark Mode */
var clicks = 0;
$('#modetog').click(function() {
if (clicks % 2 === 0){
document.querySelector('body').classList.add('isdark');
} else{
document.querySelector('body').classList.remove('isdark');
}++clicks;
});
</script>
P.S.: I am still learning JavaScript, sorry for asking stupid questions. I didn't understand even after searching on the internet.
Upvotes: 1
Views: 1070
Reputation: 96
You can use the localStorage api (reference):
// Code to save setting
localStorage.setItem('darkTheme', '1'); // Here you can put any string you want, I just chose 2 understandable ones
// Code to retrieve the setting
localStorage.getItem('darkTheme');
Edit: implementing the request of the comment down here
You can simply loop through the components of your page and set their style to match the selected theme (although loading different css is more performant and advised, it would require editing a good chunk of your current code)
const theme = localStorage.getItem('darkTheme');
if (theme) {
// Runs only if darkTheme is set to 1, or any truthy value
// (see https://developer.mozilla.org/en-US/docs/Glossary/Truthy for reference)
document.querySelector('body').classList.add('isdark');
clicks++; // This is to keep your theme switcher working: if the page starts dark and the user clicks to change the theme you want to revert back to light
}
To incorporate this in your code:
/* Dark Mode */
var clicks = 0;
const theme = localStorage.getItem('darkTheme');
if (theme) {
// Runs only if darkTheme is set to 1, or any truthy value
// (see https://developer.mozilla.org/en-US/docs/Glossary/Truthy for reference)
document.querySelector("body").classList.add("isdark");
clicks++; // This is to keep your theme switcher working: if the page starts dark and the user clicks to change the theme you want to revert back to light
}
$('#modetog').click(function() {
if (clicks % 2 === 0){
document.querySelector('body').classList.add('isdark');
localStorage.setItem('darkTheme', '1');
} else{
document.querySelector('body').classList.remove('isdark');
localStorage.setItem('darkTheme', '0');
}
++clicks;
});
Upvotes: 4