Saving Application State for a Single Session - J Query

Problem
You want to persist data on the client only until the current session is ended, i.e., the window or tab is closed.

Solution

In this example there are two HTML pages. Each page contains a set of selectable elements. When elements are selected and deselected, the state of the page is persisted. By navigating to and from the two pages, you can see how the state of any given page can be maintained as a user navigates through a website. The sessionStorage object is used for data that doesn’t require persisting between a user’s subsequent visits:

Each of the two HTML pages (one.html and two.html) have the same content. The following JavaScript code takes care of managing the state of each page, such that each page reflects past user manipulation:

When the document is loaded, the session Storage object is queried for keys comprising the current URL and the id of each of the selectable squares. Each square has a CSS class applied if appropriate. When a square is clicked, its display is affected by toggling a CSS class, and its state is persisted accordingly. Each square’s state is persisted using a key generated from the current URL and current element id pair.

Discussion
Similar session-delimited client-side storage is available when using the jStore plugin from the previous recipe. By using jStore, you gain the benefits of cross-browser compatibility. This recipe will only work in Internet Explorer 8.0 and Firefox 2.0 or higher. Safari 3.1 doesn’t have this feature, though future versions are slated to include it.
The DOM storage API is attractive in cases where broad browser compatibility isn’t a concern Applications developed for internal company intranets may fall into this category. It is also part of the upcoming HTML5 specification. In the future its availability is likely to spread. Using a built-in storage API has the benefit of incurring no overhead from additional JavaScript code. The minified jStore plugin and jStore.swf flash component are 20 KB in size.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics