Hello I have made this js code to change the view from List to Grid and the opposite as well but I want to keep the current view state after refreshing the page, I have seen many videos talking about cookie and localStorage but I don't know how to use them since I am still beginner in programming could you tell me how to do ?
script.js:
let x = document.getElementById('x');
let z = document.getElementById('z');
x.addEventListener('click', function() {
let className = z.className;
if (className == 'list') {
z.className = 'grid';
}else{
z.className = 'list';
}
});
index.php:
<i class="" id="x"></i>
<div class="list" id="z">
.
centent
.
</div>
localstorage is used as key-value pairs, both being always strings.
you can use localStorage.setItem('view-setting', 'list').
this will create a localstorage variable named view-setting and will define its value as list. You can fetch the data using localStorage.getItem('view-setting'). Similarly items can be deleted using localStorage.removeItem('view-setting').
So after setting the view in localStorage, you can fetch it and on reload check its last stage and add conditionals in HTTP accordingly.
You can get further help from:
Loading JS LocalStorage into PHP Variable
or
https://www.w3schools.com/html/html5_webstorage.asp
You can:
localStoragelet x = document.getElementById('x');
let z = document.getElementById('z');
let cl = localStorage.getItem("class");
if (cl !== z.className) z.className = cl;
x.addEventListener('click', function() {
let className = z.className;
if (className == 'list') {
z.className = 'grid';
}else{
z.className = 'list';
}
localStorage.setItem("class", z.className);
});
Since stackoverflow.com considers direct operation with localStorage to be unsafe, I had to create a Fiddle for proof-of-concept. See here: https://jsfiddle.net/q68vnctL/
You can test by running it, clicking the "Click Me!" button as many times as you like, click on "Run" again and see that the color remains whatever it was.