Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

HTML Local Storage

Posted in HTML Tutorial
Updated on Sep 08, 2024
By Mari Selvan
πŸ‘οΈ 12 - Views
⏳ 4 mins
πŸ’¬ 0
HTML Local Storage

Photo Credit to CodeToFun

πŸ™‹ Introduction

Local Storage is a feature of the Web Storage API that allows websites to store key-value pairs in a web browser, persisting even after the browser is closed. It is an ideal solution for storing small amounts of data that should remain available across sessions.

Unlike cookies, data stored in Local Storage is not sent with every HTTP request, making it more efficient for storing client-side data.

🀷 What Is Local Storage?

Local Storage is a part of the browser's Web Storage API that allows you to store data locally on the user's computer.

Data stored in Local Storage does not expire unless explicitly removed, making it persistent even when the browser or device is restarted.

It stores data as key-value pairs and is particularly useful for saving user preferences, theme settings, or session data across visits.

πŸ”‘ Key Features of Local Storage

  • Key-Value Storage: Stores data as simple key-value pairs.
  • Persistent Storage: Data remains available across browser sessions.
  • Synchronous API: All operations are synchronous, unlike IndexedDB.
  • Limited Size: Each domain can typically store up to 5MB of data.
  • No Expiration: Data persists until manually deleted by the application or the user.

πŸ€” How to Use Local Storage

Local Storage is easy to use with JavaScript. You interact with it using the localStorage object, which provides methods to store, retrieve, and remove data. The data is stored as strings, so you need to stringify objects before storing them.

βš™οΈ Setting Data in Local Storage

To store data in Local Storage, you can use the setItem method. Here’s how you can store a simple key-value pair:

javascript
Copied
Copy To Clipboard
localStorage.setItem('username', 'JohnDoe');

You can also store objects, but since Local Storage only stores strings, you’ll need to use JSON.stringify:

javascript
Copied
Copy To Clipboard
const user = { name: 'JohnDoe', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

πŸ’Ύ Retrieving Data from Local Storage

To retrieve data, use the getItem method:

javascript
Copied
Copy To Clipboard
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe

If you are retrieving an object, you will need to parse it back into its original form using JSON.parse:

javascript
Copied
Copy To Clipboard
const user = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // Output: JohnDoe

πŸ—‘οΈ Removing Data from Local Storage

If you want to remove a specific item from Local Storage, use the removeItem method:

javascript
Copied
Copy To Clipboard
localStorage.removeItem('username');

🧹 All Data in Local Storage

You can clear all the data stored in Local Storage for your domain by using the clear method:

javascript
Copied
Copy To Clipboard
localStorage.clear();

⚠️ Limitations of Local Storage

  • Size Limit: The amount of data you can store is limited (typically around 5MB per domain).
  • Synchronous API: All Local Storage operations are blocking, which may impact performance if used improperly.
  • Security Risks: Data stored in Local Storage is not encrypted, so sensitive information should not be stored.
  • Same-Origin Policy: Local Storage data is accessible only within the same domain and protocol.

πŸ“ Example

Here’s a complete example demonstrating how to store, retrieve, and delete data using Local Storage:

HTML
Copied
Copy To Clipboard
<!DOCTYPE html>
<html>
<head>
  <title>Local Storage Example</title>
</head>
<body>
  <h1>HTML Local Storage Example</h1>
  <button id="save">Save to Local Storage</button>
  <button id="retrieve">Retrieve from Local Storage</button>
  <button id="remove">Remove from Local Storage</button>
  <button id="clear">Clear All Local Storage</button>
  <p id="output"></p>

  <script>
    document.getElementById('save').addEventListener('click', function() {
      localStorage.setItem('greeting', 'Hello, World!');
      document.getElementById('output').textContent = 'Data saved!';
    });

    document.getElementById('retrieve').addEventListener('click', function() {
      const greeting = localStorage.getItem('greeting');
      document.getElementById('output').textContent = greeting ? greeting : 'No data found';
    });

    document.getElementById('remove').addEventListener('click', function() {
      localStorage.removeItem('greeting');
      document.getElementById('output').textContent = 'Data removed!';
    });

    document.getElementById('clear').addEventListener('click', function() {
      localStorage.clear();
      document.getElementById('output').textContent = 'All data cleared!';
    });
  </script>
</body>
</html>

πŸŽ‰ Conclusion

HTML Local Storage is an easy-to-use and efficient way to store data on the client side. It is perfect for saving small amounts of persistent data without relying on external databases or cookies.

However, it’s important to be mindful of its limitations, especially when dealing with sensitive information and large datasets.

πŸ‘¨β€πŸ’» Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
πŸ‘‹ Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy