By the end of this lesson, you will be able to save data localStorage and read it whenever necessary while using JavaScript.
localStorage is a web storage feature that allows you to save data in a user’s browser. This data persists even when the browser is closed or the computer is turned off. For example, a task planner can save your tasks automatically, so you don’t lose them. Therefore, it is a handy tool when developing applications.
To save data localStorage, you use the setItem method. This method takes two parameters: the key and the value you want to store. There are various ways to use this in your projects. For example, consider using it to save user preferences or form data.
File: taskPlanner.js
// Save a task to localStorage
function saveTask() {
const taskInput = document.getElementById('taskInput').value;
localStorage.setItem('task', taskInput);
}
// Read the task from localStorage
function readTask() {
const task = localStorage.getItem('task');
document.getElementById('taskDisplay').innerText = task;
}
If you save "Buy groceries" as a task, it will display:
Buy groceries
saveTask gets the value from an input with the ID taskInput.'task'.readTask retrieves the value stored under the same key and displays it in an element with the ID taskDisplay.For your hands-on task, create a simple task planner. This planner should have an input field and a button to save tasks. When you click the button, the task should be saved using localStorage. Below your input, show the saved task so that users can view their progress.
// Save a task to localStorage
function saveTask() {
const taskInput = document.getElementById('taskInput').value;
localStorage.setItem('task', taskInput);
readTask(); // Update display
}
// Read the task from localStorage
function readTask() {
const task = localStorage.getItem('task');
document.getElementById('taskDisplay').innerText = task || 'No tasks saved.';
}
// HTML elements:
// <input id="taskInput" type="text">
// <button onclick="saveTask()">Save Task</button>
// <div id="taskDisplay"></div>
null. Always check if the value is null before proceeding with your logic.localStorage.setItem to save data and getItem to read the data back.