Local Storage in JavaScript refers to a web browser feature that allows web applications to store data persistently on a user's device. It provides a simple key-value store where developers can save and retrieve data directly within the user's browser. Local Storage is often used to store user preferences, settings, or any data that should be available between sessions or page refreshes without the need for a server.
Local Storage in JavaScript refers to a web browser feature that allows web applications to store data persistently on a user's device. It provides a simple key-value store where developers can save and retrieve data directly within the user's browser. Local Storage is often used to store user preferences, settings, or any data that should be available between sessions or page refreshes without the need for a server.
Storage Limitations Local Storage offers a larger storage capacity compared to session storage (usually around 5-10 MB, depending on the browser). However, it's important to note that this storage is limited to the user's device and domain. Different browsers may have slightly different storage limits.
Data FormatData stored in Local Storage is always in the form of key-value pairs. Both the keys and values are stored as strings. If you need to store more complex data structures, you'll need to serialize and deserialize them, typically using JSON.
Persistent Storage Unlike session storage, data stored in Local Storage persists even after the browser is closed or the user navigates away from the page. It remains available until explicitly removed by the user, cleared by the application, or until it expires.
Same-Origin Policy Local Storage follows the same-origin policy, which means that a web page can only access data stored in Local Storage by the same domain. This restriction enhances security by preventing one website from accessing another website's data.
Simple API : Local Storage provides a straightforward API for working with data:
Events : Local Storage also provides events that notify you when data changes:storage event: Fired on a different window or tab when data is changed in Local Storage. This can be used to synchronize data between different browser instances.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>LocalStorage Array Values</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="container"> <h1>CRUD with Local Storage</h1> <p>1.convert Array to strings using <mark>JSON.stringify()</mark> before storing</p> <p>2.convert them back to their original form using <mark>JSON.parse()</mark> after retrieving.</p> <hr /> <form id="dataForm"> <label for="dataInput">Enter Data</label> <input type="text" id="dataInput" /> <button type="submit">Add Data</button> </form> <div id="output"> <h2>Stored Data</h2> <ul id="dataList"></ul> </div> </div> <script src="script.js"></script> </body> </html>
<form> Element:
<label> Element:
<input> Element:
<button> Element:
document.addEventListener("DOMContentLoaded", function () { const dataForm = document.getElementById("dataForm"); const dataInput = document.getElementById("dataInput"); const dataList = document.getElementById("dataList"); loadStoredData(); dataForm.addEventListener("submit", function (e) { e.preventDefault(); const data = dataInput.value.trim(); if (data !== "") { addToLocalStorage(data); loadStoredData(); dataInput.value = ""; } else { alert("Please Enter The Data"); dataInput.focus(); } }); //Add New Data to LocalStorage function addToLocalStorage(data) { const storedData = JSON.parse(localStorage.getItem("myData")) || []; storedData.push(data); localStorage.setItem("myData", JSON.stringify(storedData)); } //Load All Data From LocalStorage function loadStoredData() { const storedData = JSON.parse(localStorage.getItem("myData")) || []; dataList.innerHTML = ""; storedData.forEach((data, index) => { /* const li = document.createElement("li"); li.textContent = data; dataList.appendChild(li); */ let output = ` <li> ${data} <div> <button class='btnEdit' data-index='${index}' >Edit</button> <button class='btnDelete'data-index='${index}' >Delete</button> </div> <li> `; dataList.innerHTML += output; }); const delButtons = document.querySelectorAll(".btnDelete"); delButtons.forEach((btn) => { btn.addEventListener("click", deleteData); }); const editButtons = document.querySelectorAll(".btnEdit"); editButtons.forEach((btn) => { btn.addEventListener("click", editData); }); } //To Delete A User from LocalStorage function deleteData() { if (confirm("Are Your Sure to Delete")) { const index = this.dataset.index; const storedData = JSON.parse(localStorage.getItem("myData")) || []; storedData.splice(index, 1); localStorage.setItem("myData", JSON.stringify(storedData)); loadStoredData(); } } //To Modify User Data function editData() { const index = this.dataset.index; const storedData = JSON.parse(localStorage.getItem("myData")) || []; const newData = prompt("Edit Username", storedData[index]); if (newData !== null) { storedData[index] = newData.trim(); localStorage.setItem("myData", JSON.stringify(storedData)); loadStoredData(); } } });
The code begins by adding an event listener for the "DOMContentLoaded" event, ensuring that the JavaScript code only runs after the HTML document has been fully loaded.
DOM elements are selected and stored in variables:
The loadStoredData function is called to load any existing data from Local Storage and display it in the "dataList" element.
An event listener is set up for the form's "submit" event. When the user submits the form, the callback function:
The addToLocalStorage function is responsible for adding new data to Local Storage. It retrieves the existing data, adds the new data, and updates Local Storage.
The loadStoredData function retrieves data from Local Storage, iterates over it, and dynamically generates list items with associated delete and edit buttons for each data item. Event listeners for delete and edit actions are added to these buttons.
The deleteData function allows users to delete a data item. It prompts for confirmation and then removes the selected data item from Local Storage. After deletion, it calls loadStoredData to refresh the data list.
The editData function enables users to modify an existing data item. It prompts for the new data, updates the item in Local Storage, and then refreshes the data list with the updated data using loadStoredData.
Overall, this code provides a simple user interface for adding, viewing, editing, and deleting data items stored in Local Storage within a web page.
To enhance the user experience, it's essential to add CSS styles to the HTML page for a visually appealing and organized presentation of content.
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap"); * { margin: 0; padding: 0; } body { font-family: "Poppins", sans-serif; background-color: #f0f0f0; } .container { max-width: 800px; background-color: #fff; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px; } h1 { text-align: center; font-weight: 500; font-size: 18px; color: crimson; text-transform: uppercase; margin-bottom: 10px; } p { margin-bottom: 10px; } hr { margin-top: 20px; margin-bottom: 20px; } mark { font-weight: bold; } h2 { font-size: 16px; font-weight: 500; color: chocolate; margin-bottom: 10px; } label, input { display: block; margin-bottom: 5px; } button { padding: 3px 6px; } #output { border-top: 1px solid #ccc; padding-top: 10px; margin-top: 10px; } #dataList { list-style-type: none; } #dataList li { display: flex; justify-content: space-between; margin-bottom: 5px; }
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions