Today, I explored JavaScript Local Storage and learned how to store, retrieve, update, and remove data directly in the browser.
Introduction – What is Local Storage?
Local Storage is a feature in JavaScript that allows us to store data in the browser. The stored data remains available even after refreshing or closing the browser.
Why Do We Need Local Storage? – Why storing data in the browser is useful.
We use Local Storage to save data in the browser so users don't lose important information when they refresh or revisit a webpage. For example, saving user preferences, theme settings, or shopping cart items.
How Local Storage Works – Understanding browser storage.
Local Storage stores data as key-value pairs in the user's browser. JavaScript provides built-in methods to save, retrieve, update, and delete data.
Important Local Storage Methods :
1.localStorage.setItem() – Store data.
2.localStorage.getItem() – Retrieve data.
3.localStorage.removeItem() – Remove specific data.
l4.ocalStorage.clear() – Remove all stored data.
Practical Example : Ecommerce website
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
span {
font-size: 20px;
font-weight: 600;
}
#parent-div {
box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
width:400px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 20px ;
gap: 30px;
}
/* div:hover {
transform: scale(1.1);
} */
img {
width: 300px;
}
.price {
text-decoration: line-through;
}
#cards {
display: grid;
grid-template-columns: /*repeat(3, minmax(0, 1fr));*/ repeat(auto-fit, minmax(400px, 1fr));
gap: 40px;
}
button {
padding: 15px 20px;
font-weight: 700;
background-color: rgb(8, 98, 216);
color: white;
border: none;
border-radius: 10px;
cursor: pointer;
}
button:hover {
background-color: rgb(17, 59, 199);
}
div {
display: flex;
gap : 20px;
}
/* #btns button {
margin-right: 20px;
} */
.cart-btn {
position: fixed;
right :0;
}
.p{
width: 200px; /* controls how much text is visible */
height: 100px;
/* overflow: scroll; hides the rest */
white-space: nowrap;
}
#cartCount {
font-size: 15px;
}
a {
border: 1px solid blue;
background-color: rgb(17, 59, 199) ;
color: white;
text-decoration: none;
padding: 10px 10px;
border-radius: 10px;
font-weight: 700;
}
</style>
</head>
<body>
<a href="viewcartpage.html" class="cart-btn">ViewCart <span id="cartCount"></span></a>
<div id = "cards">
</div>
<script>
//localStorage.removeItem("cart"); //to delete use once
//const currentCart = JSON.parse(localStorage.getItem("cart")) || []; //if theres no value empty [] shows
//console.log(currentCart);
const cart_items = JSON.parse(localStorage.getItem("cart")) || [];
let totalCount = cart_items.reduce((sum, item) => sum + item.count, 0);
document.getElementById("cartCount").innerText = totalCount;
fetch("https://dummyjson.com/products?limit=200")
.then((res) => res.json())
.then((data) => {
const productList = data.products;
console.log(productList);
for (let i = 0; i < productList.length; i++) {
const card = document.createElement("div");
card.id = "parent-div";
const elem = document.createElement("img");
elem.src = productList[i].images[0];
card.appendChild(elem);
const brandTag = document.createElement("h3");
brandTag.innerText = `Brand : ${productList[i].brand}`;
card.appendChild(brandTag);
const para = document.createElement("p");
para.innerHTML = `<span>Description :</span> ${productList[i].description}`;
card.appendChild(para);
const priceTag = document.createElement("h3");
priceTag.className = "price";
priceTag.innerText = `Price : ${productList[i].price}`;
card.appendChild(priceTag);
const btns = document.createElement("div");
const cart_btn = document.createElement("button");
cart_btn.addEventListener('click', ()=> myfunction(productList[i]));
cart_btn.innerText = "Add to cart";
btns.appendChild(cart_btn);
const buy_btn = document.createElement("button");
buy_btn.innerText = "Buy";
btns.appendChild(buy_btn);
card.appendChild(btns);
const cardsDiv = document.getElementById("cards");
cardsDiv.appendChild(card);
}
})
function myfunction(e){
let existingItem = cart_items.filter(item => item.id === e.id);
if (existingItem.length > 0) {
existingItem[0].count++;
}
else {
cart_items.push({...e, count: 1});
}
localStorage.setItem("cart", JSON.stringify(cart_items));
console.log(cart_items);
}
</script>
</body>
</html>
"Today, I learned how Local Storage helps JavaScript applications remember data even after refreshing the browser".
Top comments (0)