Introduction
In modern web development, client-side storage solutions like Local Storage have become essential for building efficient and user-friendly applications. Local Storage allows developers to store data on the user's browser, enabling features like offline access and persistent user preferences without the need for server-side databases.
In this article, we'll walk through creating a simple CRUD (Create, Read, Update, Delete) application using HTML5, JavaScript, and Local Storage. This application will allow users to store, retrieve, update, and delete key-value pairs directly in their browser.
Table of Contents
- Prerequisites
- Project Overview
- Setting Up the HTML Structure
- Styling with CSS
- Implementing JavaScript Functionality
- Final Code
- Testing the Application
- Conclusion
- Additional Resources
Prerequisites
To follow along with this tutorial, you should have:
- Basic knowledge of HTML, CSS, and JavaScript.
- A modern web browser (e.g., Chrome, Firefox, Edge).
- A text editor or IDE (e.g., Visual Studio Code, Sublime Text).
Project Overview
We will build a simple web page that:
- Provides input fields for the user to enter a key and a value.
- Offers buttons to perform Create, Read, Update, and Delete operations.
- Displays all stored key-value pairs in a table format.
- Utilizes Local Storage to persist data between sessions.
Setting Up the HTML Structure
Let's start by creating a basic HTML file with the necessary elements.
Create a file named local_storage_crud.html
and add the following code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Storage CRUD Application</title>
</head>
<body>
<h1>Local Storage CRUD Application</h1>
<input type="text" id="dataKey" placeholder="Enter Key">
<input type="text" id="dataValue" placeholder="Enter Value">
<button onclick="createData()">Create</button>
<button onclick="readData()">Read</button>
<button onclick="updateData()">Update</button>
<button onclick="deleteData()">Delete</button>
<div id="dataDisplay"></div>
</body>
</html>
Explanation:
-
Header (
<h1>
): Displays the title of the application. -
Input Fields:
-
Key Input (
#dataKey
): For entering the key. -
Value Input (
#dataValue
): For entering the value.
-
Key Input (
- Buttons: Each button triggers a JavaScript function corresponding to a CRUD operation.
-
Data Display (
#dataDisplay
): A<div>
element where we'll display the stored data.
Styling with CSS
To make the application visually appealing, we'll add some basic CSS styles.
Add the following <style>
tag within the <head>
section:
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
input, button {
margin: 5px;
padding: 8px;
font-size: 16px;
}
#dataDisplay {
margin-top: 20px;
}
table {
border-collapse: collapse;
width: 100%;
margin-top: 10px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f4f4f4;
}
button {
cursor: pointer;
}
</style>
Explanation:
- General Styles: Sets font family and margins for the body.
- Inputs and Buttons: Adds margin, padding, and font size for better usability.
- Data Display: Adds margin to separate it from the input area.
- Table Styles: Styles the table, headers, and cells for clear data presentation.
- Button Cursor: Changes the cursor to a pointer when hovering over buttons.
Implementing JavaScript Functionality
We'll now add JavaScript functions to handle each CRUD operation and to display the data.
Add the following <script>
tag just before the closing </body>
tag:
<script>
// Function to create data
function createData() {
var key = document.getElementById('dataKey').value;
var value = document.getElementById('dataValue').value;
if (key && value) {
if (localStorage.getItem(key) === null) {
localStorage.setItem(key, value);
alert('Data added to local storage.');
displayData();
} else {
alert('Key already exists. Use Update to modify the value.');
}
} else {
alert('Please enter both key and value.');
}
}
// Function to read data
function readData() {
var key = document.getElementById('dataKey').value;
if (key) {
var value = localStorage.getItem(key);
if (value !== null) {
alert('Key: ' + key + '\nValue: ' + value);
} else {
alert('No data found for the given key.');
}
} else {
alert('Please enter a key to read data.');
}
}
// Function to update data
function updateData() {
var key = document.getElementById('dataKey').value;
var value = document.getElementById('dataValue').value;
if (key && value) {
if (localStorage.getItem(key) !== null) {
localStorage.setItem(key, value);
alert('Data updated in local storage.');
displayData();
} else {
alert('No data found for the given key. Use Create to add new data.');
}
} else {
alert('Please enter both key and value.');
}
}
// Function to delete data
function deleteData() {
var key = document.getElementById('dataKey').value;
if (key) {
if (localStorage.getItem(key) !== null) {
localStorage.removeItem(key);
alert('Data deleted from local storage.');
displayData();
} else {
alert('No data found for the given key.');
}
} else {
alert('Please enter a key to delete data.');
}
}
// Function to display all data
function displayData() {
var dataDisplay = document.getElementById('dataDisplay');
dataDisplay.innerHTML = '';
if (localStorage.length > 0) {
var table = '<table><tr><th>Key</th><th>Value</th></tr>';
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
table += '<tr><td>' + key + '</td><td>' + value + '</td></tr>';
}
table += '</table>';
dataDisplay.innerHTML = table;
} else {
dataDisplay.innerHTML = 'Local storage is empty.';
}
}
// Display data when the page loads
window.onload = function() {
displayData();
}
</script>
Create Data
Function: createData()
- Purpose: Adds a new key-value pair to Local Storage if the key doesn't already exist.
-
Logic:
- Retrieves the key and value from input fields.
- Checks if both key and value are provided.
- Checks if the key already exists in Local Storage.
- Stores the key-value pair if the key is new.
- Calls
displayData()
to refresh the displayed data.
Read Data
Function: readData()
- Purpose: Retrieves and displays the value associated with a given key.
-
Logic:
- Retrieves the key from the input field.
- Checks if the key is provided.
- Fetches the value from Local Storage.
- Displays an alert with the key and value or an error message.
Update Data
Function: updateData()
- Purpose: Updates the value of an existing key in Local Storage.
-
Logic:
- Retrieves the key and new value from input fields.
- Checks if both key and value are provided.
- Checks if the key exists in Local Storage.
- Updates the value if the key exists.
- Calls
displayData()
to refresh the displayed data.
Delete Data
Function: deleteData()
- Purpose: Removes a key-value pair from Local Storage.
-
Logic:
- Retrieves the key from the input field.
- Checks if the key is provided.
- Checks if the key exists in Local Storage.
- Removes the key-value pair if the key exists.
- Calls
displayData()
to refresh the displayed data.
Display Data
Function: displayData()
- Purpose: Displays all key-value pairs stored in Local Storage in a table.
-
Logic:
- Clears the existing content in the
#dataDisplay
element. - Checks if Local Storage has any data.
- Iterates through all keys in Local Storage.
- Builds an HTML table with all key-value pairs.
- Inserts the table into the
#dataDisplay
element.
- Clears the existing content in the
Note: The window.onload
event ensures that the data is displayed as soon as the page loads.
Final Code
Combining all the sections, your final HTML file should look like this:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Storage CRUD Application</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
input, button {
margin: 5px;
padding: 8px;
font-size: 16px;
}
#dataDisplay {
margin-top: 20px;
}
table {
border-collapse: collapse;
width: 100%;
margin-top: 10px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f4f4f4;
}
button {
cursor: pointer;
}
</style>
</head>
<body>
<h1>Local Storage CRUD Application</h1>
<input type="text" id="dataKey" placeholder="Enter Key">
<input type="text" id="dataValue" placeholder="Enter Value">
<button onclick="createData()">Create</button>
<button onclick="readData()">Read</button>
<button onclick="updateData()">Update</button>
<button onclick="deleteData()">Delete</button>
<div id="dataDisplay"></div>
<script>
// Function to create data
function createData() {
var key = document.getElementById('dataKey').value;
var value = document.getElementById('dataValue').value;
if (key && value) {
if (localStorage.getItem(key) === null) {
localStorage.setItem(key, value);
alert('Data added to local storage.');
displayData();
} else {
alert('Key already exists. Use Update to modify the value.');
}
} else {
alert('Please enter both key and value.');
}
}
// Function to read data
function readData() {
var key = document.getElementById('dataKey').value;
if (key) {
var value = localStorage.getItem(key);
if (value !== null) {
alert('Key: ' + key + '\nValue: ' + value);
} else {
alert('No data found for the given key.');
}
} else {
alert('Please enter a key to read data.');
}
}
// Function to update data
function updateData() {
var key = document.getElementById('dataKey').value;
var value = document.getElementById('dataValue').value;
if (key && value) {
if (localStorage.getItem(key) !== null) {
localStorage.setItem(key, value);
alert('Data updated in local storage.');
displayData();
} else {
alert('No data found for the given key. Use Create to add new data.');
}
} else {
alert('Please enter both key and value.');
}
}
// Function to delete data
function deleteData() {
var key = document.getElementById('dataKey').value;
if (key) {
if (localStorage.getItem(key) !== null) {
localStorage.removeItem(key);
alert('Data deleted from local storage.');
displayData();
} else {
alert('No data found for the given key.');
}
} else {
alert('Please enter a key to delete data.');
}
}
// Function to display all data
function displayData() {
var dataDisplay = document.getElementById('dataDisplay');
dataDisplay.innerHTML = '';
if (localStorage.length > 0) {
var table = '<table><tr><th>Key</th><th>Value</th></tr>';
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
table += '<tr><td>' + key + '</td><td>' + value + '</td></tr>';
}
table += '</table>';
dataDisplay.innerHTML = table;
} else {
dataDisplay.innerHTML = 'Local storage is empty.';
}
}
// Display data when the page loads
window.onload = function() {
displayData();
}
</script>
</body>
</html>
Testing the Application
-
Open the HTML File:
- Double-click the
local_storage_crud.html
file to open it in your default browser. - Alternatively, right-click the file and choose "Open with" followed by your preferred browser.
- Double-click the
-
Create Data:
- Enter a key (e.g.,
username
) and a value (e.g.,john_doe
). - Click the Create button.
- An alert should confirm the addition, and the table will display the new data.
- Enter a key (e.g.,
-
Read Data:
- Enter the key you just added (e.g.,
username
). - Click the Read button.
- An alert will display the key and its associated value.
- Enter the key you just added (e.g.,
-
Update Data:
- Enter the same key (e.g.,
username
) and a new value (e.g.,jane_doe
). - Click the Update button.
- An alert should confirm the update, and the table will reflect the new value.
- Enter the same key (e.g.,
-
Delete Data:
- Enter the key you wish to delete (e.g.,
username
). - Click the Delete button.
- An alert should confirm the deletion, and the data will be removed from the table.
- Enter the key you wish to delete (e.g.,
-
View All Data:
- The table under the buttons displays all key-value pairs.
- The table updates automatically after each operation.
Note: The data persists even if you refresh the page or close and reopen the browser, as long as Local Storage isn't cleared.
Conclusion
Congratulations! You've successfully created a simple CRUD application using HTML5 and Local Storage. This project demonstrates how you can leverage client-side storage to build interactive and stateful web applications without server-side dependencies.
Key Takeaways:
-
Local Storage:
- Provides a way to store data locally within the user's browser.
- Data persists between sessions unless explicitly cleared.
- Useful for saving user preferences, offline data, and more.
-
CRUD Operations:
- Fundamental operations for managing data.
- Implemented using straightforward JavaScript functions.
-
User Interface:
- Simple and intuitive UI enhances user experience.
- Real-time updates to the data display keep users informed.
Additional Resources
- MDN Web Docs:
- W3Schools Tutorials:
- Further Reading:
Feel free to expand upon this project by adding features like data validation, search functionality, or integrating it with server-side storage for a full-stack application. Happy coding! and askink me for askpedromartins.com