Local Storage using jQuery

Storing information locally on a user’s computer is a powerful strategy for a developer who is creating something for the Website. In this Example, we will look at how to store information on a computer to read later.

  • localStorage is synchronous in nature, meaning when it loads it can block the main document from rendering
  • localStorage does file I/O meaning it writes to your hard drive, which can take long depending on what your system does (indexing, virus scanning…)
<!DOCTYPE html>
<html>
<head>

<style>
#test
{
margin-top: 10px;
padding: 10px;
border: 1px solid black;
}
</style>

<script>
// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function(){

// check the new text
var newText = $(this).text();

// overwrite the old text
localStorage.setItem('test', newText);

// test if it works
alert( localStorage.getItem('test') );
})

</script>
</head>
<body>

<lable> Please Enter Your Word: </lable><br>
<div id="test" contenteditable="true">Hello world</div>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *