Brandon
Brandon

Reputation: 21

using local storage to remember css display value

I have a checklist built in html/javascript and you can show/hide each section of the checklist by clicking an arrow but I want to use local Storage to remember if each item was shown or hidden last time the app was used and then load the page exactly as it was last time it was used, So if all checklist items where shown last time the user used the app then I want all the checklist items to be shown next time they use the app. but i'm not sure how to get javascript/localstorage to remember the css display value. Maybe that's not the best way to go about solving this problem. Any ideas or tips would be appreciated.

Upvotes: 0

Views: 1066

Answers (2)

JasonWilczak
JasonWilczak

Reputation: 2403

To use local storage, you need to remember that strings are stored. You could use a JSON object, stringified, to store the data.

Use the checkbox id as the property and it's display style as the value:

First get the checkbox by id (could be done in a loop):

var checkbox =document.getElementById('someCheckbox');

Then you need to get your current storage string:

var myStorageData = localStorage.getItem('mydata');

and check if it exists, and if so, parse it to an object, otherwise make a new object:

if(myStorageData)    {
   myStorageData = JSON.parse(myStorageData);
}
else    {
   myStorageData = {};
}

Finally, set the properties of the object, based on the id of the checkbox and set the storage with the new values:

myStorageData[checkbox.id] = checkbox.style.display;

localStorage.setItem('myData',JSON.stringify(myStorageData));

To change your checkbox, you will just get the item out and set the style:

var myStorageData = localStorage.getItem('mydata');
document.getElementById('somecheckbox').style.display = JSON.parse(myStorageData).somecheckbox;

NOTE You will definitely want to wrap some of the logic into functions for reuse and do some defensive coding before parsing to avoid exceptions.

Here is a Fiddle that generally demonstrates the above answer.

Upvotes: 1

kanzelm3
kanzelm3

Reputation: 535

Don't use it to store the css value, simply use it to store the last state of the checkbox. So if they check the checkbox, store a value in localstorage as checked for that checkbox. And then when the page loads, get the state of all of the checkboxes from localstorage and you can toggle them all to their previous state. The state of the checkbox would drive the css class that gets applied to them.

Upvotes: 0

Related Questions