How to persist collapse (show/hide) state of toggle() with LocalStorage

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

How to persist collapse (show/hide) state of toggle() with LocalStorage

Hi,

I have a form that use this collapse.js to show/hide fieldsets with toggle(). Those who are familiar with Django will recognize this function because its exactly the one used in django admin. Now, I would like to persist the show/hide fieldsets state when the form is submitted and the page reloaded. According to this question, this can be achieve with a window.localStorage. How should I modify collapse.js to achieve this?

The point of localstorage in this case is so that when the user leaves ur page (leaving all running JS state behind), the toggled state will still be saved in the user's localstorage (if available in their browser).

In your hide function, you need to set a piece of data in localstorage that says the state is hidden. In your show function, you need to set a piece of data in localstorage that says the state is showing. Then whenever the view is toggled, localstorage is storing the data. Now, let's change the subject to when the page first loads for any given user.

- First, you would have to check if the user agent supports localstorage, If not, then just let the app start as it would normally if localstorage never existed. Nothing we can do about that unless u want to use cookies- but that's beyond this post.

- Second, if the agent supports localstorage, then you need a script that will set the state of all the toggles to that of the ones in localstorage. You need to retrieve data from localstorage, you need to use that data to set the toggles.

- Third, .. You need to test and make sure the first and second steps work.

Ok I have managed to make it works. However, I still have a little bug that I cant fix yet. When the localStorage is true, the fieldset is displayed on reload. That is the expected behaviour. The bug is that the user must click two-times on "Hide" to make the fieldset toggled again. After the double-click, the user have to click only one time on "Hide" or "Show" to toggle the fieldset.

Here, the problem was jQuery toggle doesn't see the localstorage. I created functions for show and hide, and I placed the toggle function in a conditional statement, swapping show and hide if the item is supposed to show from local storage. Also, in the same condition, I invoke 'show' to show the item. I do this rather than constructing the items differently based on local storage. So basically, what I'm doing with this code is simulating a click on "show" when the data is found in local storage.