View video tutorial
HTML Local Storage
HTML
The localStorage object is used to permanently store data..
Local Storage
Local storage uses the localStorage object to store data on a permanent basis.
Stored local data will be available later until it is removed or cleared.
Local Storage important methods
localStorage.setItem(key, value) saves the value associated with a key.
localStorage.getItem(key) retrieves values associated with the key.
localStorage.removeItem(key) removes the value associated with the key.
localStorage.clear() removes all key / value pairs from localStorage.
Learning with HTML Editor "Try it Now"
You can edit the HTML code and view the result using online editor.
Example
<!DOCTYPE html>
<html>
<head>
<title>Local Storage Example</title>
<meta charset="utf-8" />
<style>
button {
width: 150px;
height: 50px;
background-color: cornflowerblue;
font-size: 14pt;
color: white;
border-radius: 10px;
}
button:hover {
background-color: rgb(17, 87, 218);
color: white;
}
</style>
<script>
// Check if the localStorage object exists
function store() {
if (localStorage) {
// Store data
localStorage.setItem("name", "w3context");
// Retrieve data
alert("Hello, " + localStorage.getItem("name"));
} else {
alert("Sorry, your browser do not support local storage.");
}
}
function show() {
if (localStorage) {
// Retrieve data
alert("Hello, " + localStorage.getItem("name"));
} else {
alert("Sorry, this browser do not support local storage.");
}
}
function remove() {
if (localStorage) {
// remove data
localStorage.removeItem("name");
alert("data removed");
} else {
alert("Sorry, this browser do not support local storage.");
}
}
function cleared() {
if (localStorage) {
// clear data
localStorage.clear();
alert("All data cleared");
} else {
alert("Sorry, this browser do not support local storage.");
}
}
</script>
</head>
<body>
<h2>HTML Local Storage Example</h2>
<p>Click this button to trigger a function.</p>
<button onclick="store()">Store</button>
<button onclick="remove()">Remove</button>
<button onclick="cleared()">Clear</button>
<button onclick="show()">Show</button>
</body>
</html>
Click on the "Try it Now" button to see how it works.