Skip to content

Instantly share code, notes, and snippets.

@avermeulen
Last active June 7, 2018 08:35
Show Gist options
  • Save avermeulen/93c0a834ad70f0c222f4c9b147b24221 to your computer and use it in GitHub Desktop.
Save avermeulen/93c0a834ad70f0c222f4c9b147b24221 to your computer and use it in GitHub Desktop.
What is localStorage and how to use it.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
.name {
font-size: 2em;
}
</style>
</head>
<body>
<div class="name">
</div>
<input type="text" name="" value="" class="enterName">
<button type="button" name="button" class="addBtn">Add name</button>
</body>
<script src="index.js" charset="utf-8"></script>
</html>
var nameElem = document.querySelector('.name');
var addBtn = document.querySelector('.addBtn');
var enterNameElem = document.querySelector('.enterName');
// var names = ['Banele', 'Yegan', 'Phindi'];
// console.log(JSON.stringify(names));
var map = {
"Banele" : 6,
"Andre" : 3
}
localStorage['map'] = JSON.stringify(map);
var myNames = [];
// take the names from localStorage
if (localStorage['myNames']){
myNames = JSON.parse(localStorage['myNames']);
}
// then print them on the screen
for (var i = 0; i < myNames.length; i++) {
var name = myNames[i];
addName(name);
}
addBtn.addEventListener('click', function(){
var theName = enterNameElem.value;
addName(theName);
myNames.push(theName);
localStorage['myNames'] = JSON.stringify(myNames);
});
function addName(name){
nameElem.innerHTML += name + "<br>"
}
var names = JSON.parse(localStorage['name']);
for (var i = 0; i < names.length; i++) {
var name = names[i];
console.log(name);
}
// nameElem.innerHTML = ;

localStorage workshop

What is localStorage

Is a way for the browser to remember stuff. That it want to use later.

sessionStorage vs localStorage

How do I use localStorage?

var names = ["Ayabonga"];

What we know

  • localStorage only stores strings
    • as a result one need to convert the stored string into an Object using JSON.parse
    • to store an Object as a string we need to use JSON.stringify

This confuses me

  • The word localStorage - it's used in to many places. Github got it a well :-(

I want to know

  • Where I can use localStorage?
  • How can I use it?
  • About the syntax of JSON?

Using localStorage tips

  • Get what is in the localStorage store it into a variable.
  • Be sure to convert the variable into an JS Object using JSON.parse - you might need to use parseFloar or Number when you are working with a number.
  • When storing objects to localStorage be sure to use JSON.stringify to convert it into a string to be stored.
  • You can use a for loop to test that your data is read from localStorage correctly.  * if you see alot of lines below each other it means that you read a string from localStorage and you didn't convert that into a list of objects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment