let carts = document.querySelectorAll('.add-cart'); let products = [ { name: "Red Backpack", tag: "redbackpack", price: 2500, inCart: 0 }, { name: "Black Shirt", tag: "blackshirt", price: 1500, inCart: 0 }, { name: "Gucci Shoes", tag: "guccishoes", price: 5000, inCart: 0 }, { name: "White Shirt", tag: "whiteshirt", price: 2000, inCart: 0 }, { name: "White shirt", tag: "whitesmart", price: 2000, inCart: 0 }, { name: "Female hand bag", tag: "femalebag", price: 3500, inCart: 0 }, { name: "Ladies Shoes", tag: "ladiesshoes", price: 3000, inCart: 0 } ]; for(let i=0; i< carts.length; i++) { carts[i].addEventListener('click', () => { cartNumbers(products[i]); totalCost(products[i]); }); } function onLoadCartNumbers() { let productNumbers = localStorage.getItem('cartNumbers'); if( productNumbers ) { document.querySelector('.cart span').textContent = productNumbers; } } function cartNumbers(product, action) { let productNumbers = localStorage.getItem('cartNumbers'); productNumbers = parseInt(productNumbers); let cartItems = localStorage.getItem('productsInCart'); cartItems = JSON.parse(cartItems); if( action ) { localStorage.setItem("cartNumbers", productNumbers - 1); document.querySelector('.cart span').textContent = productNumbers - 1; console.log("action running"); } else if( productNumbers ) { localStorage.setItem("cartNumbers", productNumbers + 1); document.querySelector('.cart span').textContent = productNumbers + 1; } else { localStorage.setItem("cartNumbers", 1); document.querySelector('.cart span').textContent = 1; } setItems(product); } function setItems(product) { // let productNumbers = localStorage.getItem('cartNumbers'); // productNumbers = parseInt(productNumbers); let cartItems = localStorage.getItem('productsInCart'); cartItems = JSON.parse(cartItems); if(cartItems != null) { let currentProduct = product.tag; if( cartItems[currentProduct] == undefined ) { cartItems = { ...cartItems, [currentProduct]: product } } cartItems[currentProduct].inCart += 1; } else { product.inCart = 1; cartItems = { [product.tag]: product }; } localStorage.setItem('productsInCart', JSON.stringify(cartItems)); } function totalCost( product, action ) { let cart = localStorage.getItem("totalCost"); if( action) { cart = parseInt(cart); localStorage.setItem("totalCost", cart - product.price); } else if(cart != null) { cart = parseInt(cart); localStorage.setItem("totalCost", cart + product.price); } else { localStorage.setItem("totalCost", product.price); } } function displayCart() { let cartItems = localStorage.getItem('productsInCart'); cartItems = JSON.parse(cartItems); let cart = localStorage.getItem("totalCost"); cart = parseInt(cart); let productContainer = document.querySelector('.products'); if( cartItems && productContainer ) { productContainer.innerHTML = ''; Object.values(cartItems).map( (item, index) => { productContainer.innerHTML += `