ZaZaKi, a web developer Between Manchester UK & Rotterdam NL. © 2015-2024.

jQuery localStorage explained

This example demonstrate how the localStorage works.

click on Append text button  several times to append some texts to the container called box and refresh the page you will the the appended texts disappears too but if you  press the Save to the localStorage button and refresh page the texts inside the box container will stay.

Press the Remove the localStorage button to remove the localStorage.


<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){

// Triggers append
$("#append").click(function(){
// appends the text <h1>Appended text.<\/h1> to the .box
$(".box").append(" <h1>Appended text.<\/h1>");
});

//Triggers localStorage.setItem
$("#saveToLocalStorage").click(function(){

// localStorage set Item (localStorageName) and saves ( $(".box").html() )
localStorage.setItem("localStorageName", $(".box").html());

});

// Triggers localStorage.removeItem
$("#removeSavedLocalStorage").click(function(){

// removes ( localStorageName ) from browser memory
localStorage.removeItem("localStorageName");

// reloads the page
location.reload();

});

// if the localStorageName is SET or not NULL
if(localStorage.getItem('localStorageName') !== null) {

// Triggers or call the saved localStorage by name localStorageName
$(".box").html(localStorage.getItem("localStorageName"));
}

});
</script>
<title></title>
</head>
<body>
<p><button id="saveToLocalStorage">Save to the localStorage</button></p>
<p><button id="removeSavedLocalStorage">Remove the localStorage</button></p>
<p><button id="append">Append text</button></p>
<p class="box"></p>
</body>
</html>

Categroy:
Front-end , HTML , javascripts , JQuery