Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a Javascript variable for later usage?

I was wondering if there were a way to save one or more javascript variables to the local machine and then call on them later?

var a = b

and then when you go back to the webpage it remembers the value that B was?

like image 203
Comms Avatar asked Nov 28 '22 11:11

Comms


1 Answers

If you mean in a web browser, there are two options:

  • Cookies

  • Web storage (in your case, specifically, "local storage" as opposed to "session storage")

Cookies are universally supported by browsers, although users can turn them off. The API to them in JavaScript is really, really bad. The cookies also get sent to your server, so they increase the size of requests to your server, but can be used both client- and server-side.

Setting a cookie is easy, but reading a cookie client-side is a pain. Look at the MDN page above for examples.

Web storage is supported by all major modern browsers (including IE8 and up). The API is much better than cookies. Web storage is purely client-side, the data is not sent to the server automatically (you can, of course, send it yourself).

Here's an example using web storage: Live Copy

<label>Value: <input type="text" id="theValue"></label>
<input type="button" id="setValue" value="Set">
<script>
(function() {
  // Use an input to show the current value and let
  // the user set a new one
  var input = document.getElementById("theValue");

  // Reading the value, which was store as "theValue"
  if (localStorage && 'theValue' in localStorage) {
    input.value = localStorage.theValue;
  }

  document.getElementById("setValue").onclick = function () {
    // Writing the value
    localStorage && (localStorage.theValue = input.value);
  };
})();
</script>
like image 63
T.J. Crowder Avatar answered Dec 09 '22 20:12

T.J. Crowder