Reputation: 33
How to write localStorage script which will remember the value of turning odometer...so that each time the user visits the site again , the odometer will resume on the value on which odometer was at when the user left the site? I'm beginner in javascript so please understand...
This is my code: https://jsfiddle.net/aht87opr/17/
I've found the following code which might help with my case: http://jsfiddle.net/Jonathan_Ironman/Hn7jc/
$('button').click(function() {
var mefedron = myOdometer.get();
$('#value').text(mefedron);
});
Upvotes: 0
Views: 3125
Reputation: 4007
localStorage
has a few ways to get and set values to the browser. The simplest is treating it like a regular object.
localStorage.distance = 55;
you can then retrieve the value by accessing the property name you created earlier.
console.log(localStorage.distance); // "55"
Notice that localStorage.distance
was set as a number but when accessed was a string. If you only need to store a number you could pass the string through a function like parseInt()
.
console.log(parseInt(localStorage.distance)); // 55
create an object model of your odometer.
var odometer = { distance: 55, timeForOilChange: false };
Then write to the localStorage
passing your model through JSON.stringify
localStorage.odometer = JSON.stringify(odometer);
and read the value back out using JSON.parse
console.log(JSON.parse(localStorage.odometer));
// { distance: 55, timeForOilChange: false }
Upvotes: 0
Reputation: 844
Nicely done on the odometer, looks good. Local storage is simple. To set local storage:
localStorage.setItem("key", "value");
To get local storage:
var number = localStorage.getItem("key");
Be sure to try getting the local storage first so you can handle any null errors.
Upvotes: 2