In this short tip post, we will learn how to use local storage API in JavaScript.
Objective
We need to store some information in the browser in a persistent manner i.e it should not be deleted after the browser is closed.
Approach
We can use local storage API of the browser to store our information. We can access local storage using JavaScript.
Local storage stores the information in a key and value format. It stores only strings, so the conversion of any other data format is a programmer responsibility.
Code
Here is the code.
HTML
JavaScript
if (typeof(Storage) !== "undefined") {
localStorage.setItem('name','Shahid');
localStorage.setItem('city','Mumbai');
localStorage.setItem('country','India');
alert('data added in localstorage');
} else {
alert('local storage not supported');
}
}
Check out the codepen for the live demo.
See the Pen
local storage by Shahid Shaikh (@codeforgeek)
on CodePen.
In order to check the local storage values, open the chrome developer tool and go to Applications menu to check the value.
Love JavaScript? Learn more about it here.