-1

Let's say I have an HTML page with several hidden divs, and I use javascript functions to hide and show these divs accordingly.

When the user refreshes the webpage it will go back to the original state. I do not want this happen. Any way to load the same state on refresh?

2 Answers2

1

You could save the input values using cookies or HTML Web Storage. Then check your stored values when the page loads. HTML Web Storage is newer and IMO easier to work with.

There are 2 different types of web storage.

  • window.localStorage - stores data with no expiration date
  • window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

Basics

Web storage is stored in key/value pairs.

localStorage.setItem("lastname", "Smith"); // Store

document.getElementById("result").innerHTML = localStorage.getItem("lastname"); // Retrieve

localStorage.removeItem("lastname"); Delete

Its really that simple. Here is more info on HTML Web Storage. Basically all you need to do is create a web storage item for each of the items you want to save the state of. Then in your JS functions that show/hide items just update the state.

FYI

You can view local storage in chrome's toolbar by going to Application > Storage.

enter image description here

RiddleMeThis
  • 1,345
  • 4
  • 16
  • 29
0

You can use browser cookies or browser storage to save a key so you can know which state was previously selected by user and show that one.

JavaScript Cookies

Also there are many packages to manage cookies:

js-cookie

Here are some examples on Stackoverflow:

How do I create and read a value from cookie?

Set cookie and get cookie with JavaScript

Navid Zarepak
  • 4,148
  • 1
  • 12
  • 26