diff --git a/index.js b/index.js index 8cad2ad6..ccc84269 100644 --- a/index.js +++ b/index.js @@ -52,4 +52,90 @@ const state = { } ], cart: [] -}; \ No newline at end of file +}; + + + +function renderGroceries(){ + const storeList = document.querySelector('.store--item-list') + storeList.innerHTML= '' + + state.items.forEach((item) =>{ + const itemElement = document.createElement('li') + itemElement.innerHTML = ` +
+ + ` + storeList.appendChild(itemElement) + }) + +} + + + + +function renderCart() { + const cartList = document.querySelector('.cart--item-list'); + cartList.innerHTML = ''; + + state.cart.forEach(cartItem => { + const cartItemElement = document.createElement('li'); + cartItemElement.innerHTML = ` +${cartItem.name}
+ + ${cartItem.quantity} + + `; + cartList.appendChild(cartItemElement); + }); +} + + +function addToCart(itemId) { + const cartItem = state.cart.find(item => item.id === itemId); + + if (cartItem) { + cartItem.quantity++; + } else { + const itemToAdd = state.items.find(item => item.id === itemId); + state.cart.push({ + ...itemToAdd, + quantity: 1 + }); + } + + renderCart(); + updateTotal(); +} + +function increaseQuantity(itemId) { + const cartItem = state.cart.find(item => item.id === itemId); + if (cartItem) { + cartItem.quantity++; + renderCart(); + updateTotal(); + } +} + +function decreaseQuantity(itemId) { + const cartItem = state.cart.find(item => item.id === itemId); + if (cartItem && cartItem.quantity > 1) { + cartItem.quantity--; + } else { + state.cart = state.cart.filter(item => item.id !== itemId); + } + renderCart(); + updateTotal(); +} + +function updateTotal() { + const total = state.cart.reduce((acc, item) => acc + (item.price * item.quantity), 0); + const totalDisplay = document.querySelector('.total-number'); + totalDisplay.textContent = `£${total.toFixed(2)}`; +} + +renderGroceries() +renderCart()