diff --git a/index.html b/index.html index 2e8d542b..bc5604ed 100644 --- a/index.html +++ b/index.html @@ -23,6 +23,7 @@

Your Cart

diff --git a/index.js b/index.js index 8cad2ad6..114d5370 100644 --- a/index.js +++ b/index.js @@ -52,4 +52,137 @@ const state = { } ], cart: [] -}; \ No newline at end of file +}; + +function getStoreItemTemplate(item) { + + const template = ` +
  • +
    + ${item.name} +
    + +
  • + `; + return template; + +} + +function getCartItemTemplate(cartItem) { + + const template = ` +
  • + ${cartItem.name} +

    ${cartItem.name}

    + + ${cartItem.quantity} + +
  • + `; + return template; + +} + +function renderStoreItems() { + + const storeItemList = document.querySelector('.store--item-list'); + storeItemList.innerHTML = ''; + + state.items.forEach(item => { + + const listItemHTML = getStoreItemTemplate(item); + const listItemElement = document.createElement('div'); + listItemElement.innerHTML = listItemHTML.trim(); + + listItemElement.querySelector('button').addEventListener('click', () => { + + addToCart(item); + + }); + + storeItemList.appendChild(listItemElement.firstElementChild); + + }); + +} + +function addToCart(item) { + + const cartItem = state.cart.find(cartItem => cartItem.id === item.id); + + if (cartItem) { + cartItem.quantity++; + } + + else { + + state.cart.push({ + ...item, + quantity: 1 + }); + + } + + renderCartItems(); + updateTotal(); + +} + +function renderCartItems() { + + const cartItemList = document.querySelector('.cart--item-list'); + cartItemList.innerHTML = ''; + + state.cart.forEach(cartItem => { + + const listItemHTML = getCartItemTemplate(cartItem); + const listItemElement = document.createElement('div'); + listItemElement.innerHTML = listItemHTML.trim(); + + listItemElement.querySelector('.remove-btn').addEventListener('click', () => { + + updateCartItemQuantity(cartItem, 'decrease'); + + }); + + listItemElement.querySelector('.add-btn').addEventListener('click', () => { + + updateCartItemQuantity(cartItem, 'increase'); + + }); + + cartItemList.appendChild(listItemElement.firstElementChild); + + }); + +} + +function updateCartItemQuantity(cartItem, action) { + + if (action === 'increase') { + cartItem.quantity++; + } + + else if (action === 'decrease') { + cartItem.quantity--; + } + + if (cartItem.quantity === 0) { + state.cart = state.cart.filter(item => item.id !== cartItem.id); + } + + renderCartItems(); + updateTotal(); + +} + +function updateTotal() { + + const total = state.cart.reduce((sum, item) => sum + item.quantity * item.price, 0); + document.querySelector('.total-number').textContent = `£${total.toFixed(2)}`; + +} + +renderStoreItems(); +renderCartItems(); +updateTotal();