Local Storage allows you to save user data in the browser. This means that if the user closes the browser window, the next time they go back to that webpage you can still access the content they entered.
In this example we're going to store the name Bob in LocalStorage and then retrieve it to display it.
In your script.js file add a new line as follows:
localStorage.setItem("name", "Bob");This does what it says on the tin, it creates a record identified with the key name and sets the value of Bob.
Now when you refresh your page nothing obvious happens…
However if you open up the Inspector and navigate to Application > LocalStorage > <project name> for Chrome, or Storage > Local Storage > <project name> for Firefox, you'll be able to see the the key and value listed out.
That's all well and good to see it in the inspector… but it's more helpful to be able to read it back out on to a page.
When you created local storage you used setItem. To get an item out you need to getItem:
localStorage.getItem("name");This will fetch the data with the key of name. Try wrapping that in a console.log()…
As you can setItem and getItem, you can remove an item with the removeItem function:
localStorage.removeItem("name");Updating local storage is easy - you just set it again.
localStorage.setItem("name", "Tom");
localStorage.setItem("name", "Harry");
localStorage.setItem("name", "Susan");After running these three lines name will be set to Susan.
In the last worksheet you explored forms and events.
- Make a text input that asks the user's name, then stores it to Local Storage
- Add a button which deletes the
namefrom Local Storage
Once you've done those, move onto Arrays and Objects.