I have created a JavaScript object.
var myObj = {};
Now as user plays-around with the application, we assign some values to this object.
myObj['Name'] = 'Mr. Gates';
myObj['Age'] = 58;
...
...
...
myObj['Role'] = 'CEO';
But whenever the page refresh's, the object looses its values.
Is there any way using HTML 5\or any other technique to persist these values across page refresh.
Yes, you have two primary choices:
Using a cookie. Cookies are easy to set from JavaScript, but a bit of a pain to read. You've said you're using jQuery; there's are a couple of jQuery plug-ins that make cookies a lot easier, if you search for "jquery cookie plugin" you'll find them.
Using web storage, which is supported by all major browsers, even IE8. You have two choices: "Session" storage that only lasts for this "session," and "local" storage which persists until the user clears it out or the browser decides it needs that room for something else.
That second option is quite easy to use, you can store things using JSON-formatted strings (the JSON
object is also supported by all major browsers):
Storing your object:
localStorage.yourObject = JSON.stringify(obj);
Retrieving your object (for instance, on page load), or a blank object if there's none stored:
obj = JSON.parse(localStorage.yourObject || "{}");
In the above, localStorage
is a variabl (and underlying implementation) provided by the browser for local storage. You could use sessionStorage
instead if you wanted session storage.
Here's a complete local storage example: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Local Storage</title>
</head>
<body>
<label><code>Name</code> property for our object:
<input type="text" id="txtName">
</label>
<script>
(function() {
var txtName = $("#txtName");
var obj = JSON.parse(localStorage.yourObject || '{"Name": ""}');
txtName.val(obj.Name);
// This is obviously hyperactive:
txtName.on("change keypress keyup blur paste click", function() {
obj.Name = txtName.val();
localStorage.yourObject = JSON.stringify(obj);
});
})();
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With