Horje
How to create HTML localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.


Learn localStorage Object

<script>
// Store
localStorage.setItem("lastname", "Smith");

// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
</script>

Output should be:

Learn localStorage Object

Example explained: localStorage Object

The example above could also be written like this:

// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

Output should be:

The example above could also be written like this:

The syntax for removing the 'lastname' localStorage item is as follows:

<script>
 localStorage.removeItem("lastname");
</script>

Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!

The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:

<script>
if (localStorage.clickcount) {
  localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
  localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s)."; 
</script>

Output should be:






Related Articles
What is HTML Web Storage API HTML Web Storage API
What is HTML Web Storage? HTML Web Storage API
What Browsers will Support HTML Web Storage API HTML Web Storage API
How to create HTML Web Storage Objects HTML Web Storage API
How to create HTML localStorage Object HTML Web Storage API
How to create HTML sessionStorage Object HTML Web Storage API

Single Articles
Learn localStorage ObjectHTML Web Storage API
Example explained: localStorage ObjectHTML Web Storage API
The example above could also be written like this:HTML Web Storage API
The syntax for removing the 'lastname' localStorage item is as follows:HTML Web Storage API

Read Full:
HTML Web Storage API
Category:
Web Tutorial
Sub Category:
HTML Web Storage API
Uploaded:
1 year ago
Uploaded by:
Admin
Views:
49


Reffered: https://www.w3schools.com/html/html5_webstorage.asp

Share on: