Assignments Of Day 16: Local Storage and Session Storage
Assignment
1: Storing and Retrieving User Information in localStorage
Problem: Create
a form where a user can enter their name and email. After submitting, store
this information in localStorage. When the page is reloaded, retrieve and
display the stored information in a div element.
Step-by-Step
Solution:
1. Create
HTML Form: Create a simple form with input fields for the name and email, and a
button to submit the data.
2. Save Data
to localStorage: When the user submits the form, the data should
be saved into localStorage.
3. Retrieve
and Display Data: On page reload, check if data exists in
localStorage. If it does, display it inside the div.
HTML Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Store User Info</title>
</head>
<body>
<h1>User Info Form</h1>
<form
id="userForm">
<label for="name">Name:</label>
<input type="text" id="name" required>
<label for="email">Email:</label>
<input type="email" id="email" required>
<button type="submit">Submit</button>
</form>
<div
id="displayInfo"></div>
<script src="app.js"></script>
</body>
</html>
JavaScript
Code (app.js):
javascript
Copy code
document.getElementById('userForm').addEventListener('submit',
function(event) {
event.preventDefault(); //
Prevent form submission
const
name = document.getElementById('name').value;
const
email = document.getElementById('email').value;
// Store
data in localStorage
localStorage.setItem('userName', name);
localStorage.setItem('userEmail', email);
//
Display the stored data
displayStoredData();
});
function displayStoredData() {
const
name = localStorage.getItem('userName');
const
email = localStorage.getItem('userEmail');
if (name
&& email) {
document.getElementById('displayInfo').innerHTML = `Stored Name:
${name}<br>Stored Email: ${email}`;
}
}
// Display stored data on page load
window.onload = displayStoredData;
Explanation:
- The
user enters their name and email in the form. When the form is submitted,
the information is stored in localStorage using localStorage.setItem().
- On
page load, the displayStoredData() function checks if the name and email
exist in localStorage and displays them in the div.
Assignment
2: Session-Based Login System
Problem: Create
a session-based login system where the username is stored in sessionStorage.
When the user logs in, their username should be saved in sessionStorage, and
upon refreshing the page, it should display a message welcoming the user. If
the user logs out, the data should be removed from sessionStorage.
Step-by-Step
Solution:
1. Create
HTML for Login/Logout: Provide input for the username and buttons to
login and logout.
2. Store
Username in sessionStorage: Upon successful login, store the username in
sessionStorage.
3. Display
Welcome Message: After logging in, check for the username in
sessionStorage and display a welcome message.
4. Logout
Functionality: Clear the username from sessionStorage when
logging out.
HTML Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Session Login</title>
</head>
<body>
<h1>Login System</h1>
<div
id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username">
<button id="loginBtn">Login</button>
</div>
<div
id="welcomeMessage"></div>
<button id="logoutBtn"
style="display:none;">Logout</button>
<script src="app.js"></script>
</body>
</html>
JavaScript
Code (app.js):
javascript
Copy code
document.getElementById('loginBtn').addEventListener('click',
function() {
const
username = document.getElementById('username').value;
// Store
username in sessionStorage
sessionStorage.setItem('username', username);
// Show
welcome message
displayWelcomeMessage();
});
document.getElementById('logoutBtn').addEventListener('click',
function() {
// Clear
username from sessionStorage
sessionStorage.removeItem('username');
document.getElementById('welcomeMessage').textContent = "";
document.getElementById('logoutBtn').style.display = 'none';
document.getElementById('loginForm').style.display = 'block';
});
function displayWelcomeMessage() {
const
username = sessionStorage.getItem('username');
if
(username) {
document.getElementById('welcomeMessage').textContent = `Welcome,
${username}!`;
document.getElementById('logoutBtn').style.display = 'block';
document.getElementById('loginForm').style.display = 'none';
}
}
// Display welcome message on page load if the user
is logged in
window.onload = displayWelcomeMessage;
Explanation:
- When
the user logs in, the username is stored in sessionStorage and a welcome
message is displayed.
- When
the user logs out, the username is removed from sessionStorage and the
login form is shown again.
Assignment
3: Storing and Retrieving an Object in localStorage
Problem: Create
an object with user details (name, age, and email), then store the object in
localStorage. Retrieve the object from localStorage, parse it, and display the
details in a formatted message.
Step-by-Step
Solution:
1. Create a
user object: Define a JavaScript object with user details.
2. Store the
object in localStorage: Use JSON.stringify() to convert the object into a
string before storing it.
3. Retrieve
and parse the object: Use localStorage.getItem() to retrieve the string
and JSON.parse() to convert it back to an object.
4. Display
the object details: Format and display the retrieved object.
HTML Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Store User Object</title>
</head>
<body>
<h1>User Information</h1>
<div
id="userInfo"></div>
<script src="app.js"></script>
</body>
</html>
JavaScript
Code (app.js):
javascript
Copy code
// Create a user object
const user = {
name:
'Alice',
age: 28,
email:
'alice@example.com'
};
// Store the object in localStorage (convert it to
a string)
localStorage.setItem('userDetails',
JSON.stringify(user));
// Retrieve and parse the object from localStorage
let retrievedUser =
JSON.parse(localStorage.getItem('userDetails'));
// Display the user's information
if (retrievedUser) {
document.getElementById('userInfo').innerHTML = `
Name:
${retrievedUser.name} <br>
Age:
${retrievedUser.age} <br>
Email: ${retrievedUser.email}
`;
}
Explanation:
- The
object is stored in localStorage after being converted into a string with
JSON.stringify().
- When
retrieving the object, we use JSON.parse() to convert the string back into
a JavaScript object.
Assignment
4: Implementing a Simple Todo List with localStorage
Problem: Create
a simple todo list where the tasks are stored in localStorage. Allow the user
to add and remove tasks. The list should persist even after refreshing the
page.
Step-by-Step
Solution:
1. Create
HTML structure: Set up a simple form to add tasks and a list to
display them.
2. Add tasks: Use
localStorage.setItem() to store tasks.
3. Remove
tasks: Use localStorage.removeItem() to remove tasks from the list.
4. Display
tasks: On page load, retrieve tasks from localStorage and display them.
HTML Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Todo List</title>
</head>
<body>
<h1>Todo List</h1>
<input
type="text" id="taskInput" placeholder="Enter
task">
<button id="addTaskBtn">Add Task</button>
<ul
id="taskList"></ul>
<script src="app.js"></script>
</body>
</html>
JavaScript
Code (app.js):
javascript
Copy code
document.getElementById('addTaskBtn').addEventListener('click',
function() {
const
taskInput = document.getElementById('taskInput');
const
task = taskInput.value;
if (task)
{
let
tasks = JSON.parse(localStorage.getItem('tasks')) || [];
tasks.push(task);
localStorage.setItem('tasks', JSON.stringify(tasks));
taskInput.value = '';
displayTasks();
}
});
function displayTasks() {
const
tasks = JSON.parse(localStorage.getItem('tasks')) || [];
const
taskList = document.getElementById('taskList');
taskList.innerHTML = '';
tasks.forEach((task, index) => {
const
li = document.createElement('li');
li.textContent = task;
const
deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.addEventListener('click', function() {
tasks.splice(index, 1);
localStorage.setItem('tasks', JSON.stringify(tasks));
displayTasks();
});
li.appendChild(deleteBtn);
taskList.appendChild(li);
});
}
// Display tasks on page load
window.onload = displayTasks;
Explanation:
- Tasks
are stored in localStorage as a JSON string. Tasks are retrieved and
displayed when the page loads.
- The
delete button allows for removing tasks, and the list is updated by
modifying localStorage.
4o mini
You said:
give some
more to understand well as i m the beginner
ChatGPT
said:
ChatGPT
Certainly!
Here are a few more assignments and examples to help you understand Local
Storage and Session Storage concepts in JavaScript. These examples
are designed for beginners, with step-by-step solutions to explain the concepts
clearly.
Assignment
5: Saving and Displaying Multiple User Preferences (localStorage)
Problem: Create
a page where the user can select a theme (light or dark) and save their
preference in localStorage. When the page is reloaded, apply the saved theme
(either light or dark) without asking the user again.
Step-by-Step
Solution:
1. Create
HTML: Add a
dropdown or toggle to select the theme.
2. Store the
selected theme in localStorage: Save the theme choice when the
user selects it.
3. Apply the
saved theme: When the page loads, check for the saved theme in
localStorage and apply it.
HTML
Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Theme Preference</title>
<style>
body.light {
background-color: white;
color: black;
}
body.dark {
background-color: black;
color: white;
}
</style>
</head>
<body>
<h1>Select Your Theme</h1>
<select id="themeSelector">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<script src="app.js"></script>
</body>
</html>
JavaScript
Code (app.js):
javascript
Copy code
// Get the theme selector element
const themeSelector =
document.getElementById('themeSelector');
// Check if there's a saved theme in localStorage
and apply it
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
document.body.classList.add(savedTheme);
themeSelector.value = savedTheme;
}
// Listen for theme change and save it to
localStorage
themeSelector.addEventListener('change', function()
{
const
selectedTheme = themeSelector.value;
// Remove
the previous theme class
document.body.classList.remove('light', 'dark');
// Add
the new theme class and save it to localStorage
document.body.classList.add(selectedTheme);
localStorage.setItem('theme', selectedTheme);
});
Explanation:
- This
example checks for the stored theme in localStorage when the page loads
and applies it by adding a light or dark class to the body element.
- When
the user changes the theme using the dropdown, the selected theme is saved
in localStorage and applied immediately.
Assignment
6: Persistent Counter with localStorage
Problem: Create
a simple counter that can be incremented by a button. The counter value should
persist across page reloads, using localStorage.
Step-by-Step
Solution:
1. Create
HTML: Add a
button to increment the counter and a display for the counter.
2. Store and
retrieve the counter value in localStorage: When the button is clicked,
update the counter in localStorage and display it.
HTML
Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Persistent Counter</title>
</head>
<body>
<h1>Counter: <span
id="counterDisplay">0</span></h1>
<button id="incrementBtn">Increment</button>
<script src="app.js"></script>
</body>
</html>
JavaScript
Code (app.js):
javascript
Copy code
// Get the counter display and button
const counterDisplay =
document.getElementById('counterDisplay');
const incrementBtn = document.getElementById('incrementBtn');
// Retrieve the counter value from localStorage
let counter =
parseInt(localStorage.getItem('counter')) || 0;
counterDisplay.textContent = counter;
// Increment counter when the button is clicked
incrementBtn.addEventListener('click', function() {
counter++;
counterDisplay.textContent = counter;
// Save
the updated counter in localStorage
localStorage.setItem('counter', counter);
});
Explanation:
- The
counter value is stored in localStorage and is retrieved when the page
loads. If no counter value exists in localStorage, it defaults to 0.
- Every
time the button is clicked, the counter increments, and the new value is
saved in localStorage, ensuring the counter persists across page reloads.
Assignment
7: Use Session Storage to Track User's Page Views
Problem: Track
how many times a user has visited a specific page in a single session using
sessionStorage. Reset the count when the page is closed or refreshed.
Step-by-Step
Solution:
1. Create
HTML: Display
a counter that shows how many times the page has been loaded in the current
session.
2. Store and
update the count in sessionStorage: Each time the page is loaded,
increment the session count and store it in sessionStorage.
HTML
Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Page View Counter</title>
</head>
<body>
<h1>You have visited this page <span
id="viewCounter">0</span> times in this session.</h1>
<script src="app.js"></script>
</body>
</html>
JavaScript
Code (app.js):
javascript
Copy code
// Retrieve the current page view count from
sessionStorage
let pageViewCount =
parseInt(sessionStorage.getItem('pageViewCount')) || 0;
pageViewCount++;
// Update the page view counter in sessionStorage
sessionStorage.setItem('pageViewCount',
pageViewCount);
// Display the page view count
document.getElementById('viewCounter').textContent
= pageViewCount;
Explanation:
- This
example uses sessionStorage to track the page view count. Each time the
page is loaded or refreshed, the counter is incremented and updated in
sessionStorage.
- The
counter resets if the user closes the browser or the session ends.
Assignment
8: Creating a Simple Shopping Cart with localStorage
Problem: Create
a simple shopping cart where users can add products to the cart, and the cart
contents are saved in localStorage. When the page is reloaded, the cart items
should persist.
Step-by-Step
Solution:
1. Create
HTML: Set up
a list of products with "Add to Cart" buttons.
2. Store the
cart items in localStorage: When an item is added to the cart, save the cart
to localStorage.
3. Display
the cart contents: When the page is reloaded, show the cart items
saved in localStorage.
HTML
Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Shopping Cart</title>
</head>
<body>
<h1>Products</h1>
<ul
id="productList">
<li>Product 1 <button class="addToCartBtn"
data-product="Product 1">Add to Cart</button></li>
<li>Product 2 <button class="addToCartBtn"
data-product="Product 2">Add to Cart</button></li>
<li>Product 3 <button class="addToCartBtn"
data-product="Product 3">Add to Cart</button></li>
</ul>
<h2>Shopping Cart</h2>
<ul
id="cartList"></ul>
<script src="app.js"></script>
</body>
</html>
JavaScript
Code (app.js):
javascript
Copy code
const addToCartBtns =
document.querySelectorAll('.addToCartBtn');
// Retrieve cart from localStorage or initialize an
empty array
let cart = JSON.parse(localStorage.getItem('cart'))
|| [];
// Function to update the cart display
function updateCart() {
const
cartList = document.getElementById('cartList');
cartList.innerHTML = '';
cart.forEach(item => {
const
li = document.createElement('li');
li.textContent = item;
cartList.appendChild(li);
});
// Save
the cart to localStorage
localStorage.setItem('cart', JSON.stringify(cart));
}
// Event listener for adding items to the cart
addToCartBtns.forEach(btn => {
btn.addEventListener('click', function() {
const
product = this.dataset.product;
cart.push(product);
updateCart();
});
});
// Initial call to display the cart contents
updateCart();
Explanation:
- Products
can be added to the cart, and the cart is stored in localStorage as a JSON
array.
- When
the page reloads, the cart is retrieved from localStorage, and the cart
items are displayed.
- This
allows the cart contents to persist across sessions until the user clears
their browser's local storage.
Summary
and Concepts Covered:
1. localStorage: Stores
data that persists even after the browser is closed or the session ends.
2. sessionStorage: Stores
data only for the duration of a page session (i.e., it resets after the browser
tab is closed).
3. JSON
Methods: Used to convert objects into strings (JSON.stringify()) and strings
back into objects (JSON.parse()).
