Issue
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>
Solution
You can:
- load the stored class from
localStorage
- see whether it's valid and different from the current class
- store its current value upon each click
let 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.
Answered By - Lajos Arpad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.