I'm trying use to use Local storage to save whether or not my class="crt"
has been set or not for my comic's website resulting it in it either showing or not showing.
I only have a basic W3Schools JavaScript code thus far for the actual toggling of the class and it works, but I'd like to have its value saved and extended across the whole website.
function myFunction() {
var element = document.getElementById("BodyId");
element.classList.toggle("crt");
This is the HTML that will be affected
<body class="crt" id="BodyId">
I have looked briefly into how the functionality works for using Local Storage for dark/light mode toggling however because I'm not switching between two classes and being new to JavaScript I've found myself a little lost with where to go.
In my mind I believe it'd be something to do with making sure to declare the class's status as either null or positive so when the local storage checks the status it'll have two categories to choose from and save for the rest of the site.
To do what you require you can use the setItem()
and getItem()
methods of localStorage
in order to store and retrieve the state of the toggle when the button is clicked and when the page loads respectively.
Here's some example code showing how the logic can be structured:
<button id="class-toggle-button">
Toggle class
</button>
const targetElement = document.querySelector('body');
// set the toggle in localStorage when the button is clicked
document.querySelector('#class-toggle-button').addEventListener('click', e => {
const hasClass = targetElement.classList.toggle("crt");
localStorage.setItem('classApplied', hasClass);
})
// retrieve the toggle from localStorage when the page loads
if (localStorage.getItem('classApplied')) {
targetElement.classList.add('crt');
}
Here's a working example in JSFiddle as SO snippet's are sandboxed and don't allow access to localStorage.
Also, as a side note as you mentioned you were using W3Schools to learn Javascript. I'd strongly advise against this as W3Schools is a very unreliable source for a variety of reasons I won't go in to here.