Spaces:
Running
Running
document.addEventListener('DOMContentLoaded', function() { | |
// Function to get cart items from local storage | |
function getCartItems() { | |
const cartItems = localStorage.getItem('cart'); | |
return cartItems ? JSON.parse(cartItems) : []; | |
} | |
// Function to set cart items in local storage | |
function setCartItems(cartItems) { | |
localStorage.setItem('cart', JSON.stringify(cartItems)); | |
} | |
// Function to add an item to the cart | |
function addToCart(productId, quantity) { | |
const cartItems = getCartItems(); | |
const existingItem = cartItems.find(item => item.productId === productId); | |
if (existingItem) { | |
existingItem.quantity += quantity; | |
} else { | |
cartItems.push({ productId, quantity }); | |
} | |
setCartItems(cartItems); | |
updateCartUI(); | |
} | |
// Function to update item quantity in the cart | |
function updateQuantity(productId, quantity) { | |
const cartItems = getCartItems(); | |
const itemIndex = cartItems.findIndex(item => item.productId === productId); | |
if (itemIndex !== -1) { | |
cartItems[itemIndex].quantity = quantity; | |
if (cartItems[itemIndex].quantity <= 0) { | |
cartItems.splice(itemIndex, 1); // Remove item if quantity is 0 or less | |
} | |
setCartItems(cartItems); | |
updateCartUI(); | |
} | |
} | |
// Function to remove an item from the cart | |
function removeItem(productId) { | |
const cartItems = getCartItems(); | |
const itemIndex = cartItems.findIndex(item => item.productId === productId); | |
if (itemIndex !== -1) { | |
cartItems.splice(itemIndex, 1); | |
setCartItems(cartItems); | |
updateCartUI(); | |
} | |
} | |
// Function to calculate cart totals | |
function calculateTotals() { | |
const cartItems = getCartItems(); | |
let subtotal = 0; | |
// Dummy product prices (replace with actual product data) | |
const productPrices = { | |
"1": 20.00, | |
"2": 30.00, | |
"3": 40.00 | |
}; | |
cartItems.forEach(item => { | |
const productId = item.productId; | |
const quantity = item.quantity; | |
const price = productPrices[productId] || 0; // Get price from productPrices, default to 0 | |
subtotal += price * quantity; | |
}); | |
const shipping = 5.00; | |
const total = subtotal + shipping; | |
return { subtotal, shipping, total }; | |
} | |
// Function to display cart items in cart.html | |
function displayCartItems() { | |
const cartItems = getCartItems(); | |
const cartItemsContainer = document.getElementById('cart-items'); | |
if (cartItemsContainer) { | |
cartItemsContainer.innerHTML = ''; // Clear existing items | |
cartItems.forEach(item => { | |
// Dummy product data (replace with actual product data) | |
const productId = item.productId; | |
const product = { | |
id: productId, | |
title: `Product ${productId}`, | |
price: 20.00, | |
image: `https://via.placeholder.com/100` | |
}; | |
const cartItemDiv = document.createElement('div'); | |
cartItemDiv.classList.add('flex', 'items-center', 'border', 'border-gray-300', 'rounded-md', 'p-4'); | |
cartItemDiv.innerHTML = ` | |
<img src="${product.image}" alt="Product Image" class="w-24 h-24 mr-4"> | |
<div> | |
<h2 class="text-lg font-bold">${product.title}</h2> | |
<p class="text-gray-600">$${product.price.toFixed(2)}</p> | |
<div class="flex items-center mt-2"> | |
<button class="bg-gray-200 px-2 py-1 rounded-md decrease-quantity" data-product-id="${product.id}">-</button> | |
<input type="number" value="${item.quantity}" class="w-16 text-center border border-gray-300 rounded-md mx-2 quantity-input" data-product-id="${product.id}"> | |
<button class="bg-gray-200 px-2 py-1 rounded-md increase-quantity" data-product-id="${product.id}">+</button> | |
<button class="text-red-500 hover:text-red-700 ml-4 remove-item" data-product-id="${product.id}">Remove</button> | |
</div> | |
</div> | |
`; | |
cartItemsContainer.appendChild(cartItemDiv); | |
}); | |
// Add event listeners to quantity buttons and remove buttons | |
const decreaseButtons = document.querySelectorAll('.decrease-quantity'); | |
decreaseButtons.forEach(button => { | |
button.addEventListener('click', function() { | |
const productId = this.dataset.productId; | |
const quantityInput = this.parentNode.querySelector('.quantity-input'); | |
let quantity = parseInt(quantityInput.value); | |
quantity = Math.max(1, quantity - 1); // Ensure quantity is not less than 1 | |
quantityInput.value = quantity; | |
updateQuantity(productId, quantity); | |
}); | |
}); | |
const increaseButtons = document.querySelectorAll('.increase-quantity'); | |
increaseButtons.forEach(button => { | |
button.addEventListener('click', function() { | |
const productId = this.dataset.productId; | |
const quantityInput = this.parentNode.querySelector('.quantity-input'); | |
let quantity = parseInt(quantityInput.value); | |
quantity++; | |
quantityInput.value = quantity; | |
updateQuantity(productId, quantity); | |
}); | |
}); | |
const removeButtons = document.querySelectorAll('.remove-item'); | |
removeButtons.forEach(button => { | |
button.addEventListener('click', function() { | |
const productId = this.dataset.productId; | |
removeItem(productId); | |
}); | |
}); | |
} | |
} | |
// Function to update the order summary in cart.html and checkout.html | |
function updateOrderSummary() { | |
const { subtotal, shipping, total } = calculateTotals(); | |
const subtotalElements = document.querySelectorAll('#subtotal'); | |
subtotalElements.forEach(element => element.textContent = `$${subtotal.toFixed(2)}`); | |
const shippingElements = document.querySelectorAll('#shipping'); | |
shippingElements.forEach(element => element.textContent = `$${shipping.toFixed(2)}`); | |
const totalElements = document.querySelectorAll('#total'); | |
totalElements.forEach(element => element.textContent = `$${total.toFixed(2)}`); | |
} | |
// Function to handle checkout | |
function handleCheckout() { | |
const checkoutForm = document.getElementById('checkout-form'); | |
if (checkoutForm) { | |
checkoutForm.addEventListener('submit', function(event) { | |
event.preventDefault(); // Prevent form submission | |
// Simulate order processing | |
const orderId = Math.floor(Math.random() * 1000000); | |
// Store order ID in local storage | |
localStorage.setItem('orderId', orderId); | |
// Clear the cart | |
setCartItems([]); | |
// Redirect to confirmation page | |
window.location.href = '/confirmation.html'; | |
}); | |
} | |
} | |
// Function to display order confirmation details | |
function displayOrderConfirmation() { | |
const orderId = localStorage.getItem('orderId'); | |
const orderIdElement = document.getElementById('order-id'); | |
if (orderIdElement) { | |
orderIdElement.textContent = orderId; | |
} | |
} | |
// Initialize the cart page | |
if (window.location.pathname === '/cart.html') { | |
displayCartItems(); | |
updateOrderSummary(); | |
} | |
// Initialize the checkout page | |
if (window.location.pathname === '/checkout.html') { | |
updateOrderSummary(); | |
handleCheckout(); | |
} | |
// Initialize the confirmation page | |
if (window.location.pathname === '/confirmation.html') { | |
displayOrderConfirmation(); | |
} | |
}); | |
// Function to get cart items from local storage | |
function getCartItems() { | |
const cartItems = localStorage.getItem('cart'); | |
return cartItems ? JSON.parse(cartItems) : []; | |
} | |
// Function to set cart items in local storage | |
function setCartItems(cartItems) { | |
localStorage.setItem('cart', JSON.stringify(cartItems)); | |
} | |
// Function to add an item to the cart | |
function addToCart(productId, quantity) { | |
const cartItems = getCartItems(); | |
const existingItem = cartItems.find(item => item.productId === productId); | |
if (existingItem) { | |
existingItem.quantity += quantity; | |
} else { | |
cartItems.push({ productId, quantity }); | |
} | |
setCartItems(cartItems); | |
updateCartUI(); | |
} | |
// Function to update item quantity in the cart | |
function updateQuantity(productId, quantity) { | |
const cartItems = getCartItems(); | |
const itemIndex = cartItems.findIndex(item => item.productId === productId); | |
if (itemIndex !== -1) { | |
cartItems[itemIndex].quantity = quantity; | |
if (cartItems[itemIndex].quantity <= 0) { | |
cartItems.splice(itemIndex, 1); // Remove item if quantity is 0 or less | |
} | |
setCartItems(cartItems); | |
updateCartUI(); | |
} | |
} | |
// Function to remove an item from the cart | |
function removeItem(productId) { | |
const cartItems = getCartItems(); | |
const itemIndex = cartItems.findIndex(item => item.productId === productId); | |
if (itemIndex !== -1) { | |
cartItems.splice(itemIndex, 1); | |
setCartItems(cartItems); | |
updateCartUI(); | |
} | |
} | |
// Function to calculate cart totals | |
function calculateTotals() { | |
const cartItems = getCartItems(); | |
let subtotal = 0; | |
// Dummy product prices (replace with actual product data) | |
const productPrices = { | |
"1": 20.00, | |
"2": 30.00, | |
"3": 40.00 | |
}; | |
cartItems.forEach(item => { | |
const productId = item.productId; | |
const quantity = item.quantity; | |
const price = productPrices[productId] || 0; // Get price from productPrices, default to 0 | |
subtotal += price * quantity; | |
}); | |
const shipping = 5.00; | |
const total = subtotal + shipping; | |
return { subtotal, shipping, total }; | |
} | |
// Function to display cart items in cart.html | |
function displayCartItems() { | |
const cartItems = getCartItems(); | |
const cartItemsContainer = document.getElementById('cart-items'); | |
if (cartItemsContainer) { | |
cartItemsContainer.innerHTML = ''; // Clear existing items | |
cartItems.forEach(item => { | |
// Dummy product data (replace with actual product data) | |
const productId = item.productId; | |
const product = { | |
id: productId, | |
title: `Product ${productId}`, | |
price: 20.00, | |
image: `https://via.placeholder.com/100` | |
}; | |
const cartItemDiv = document.createElement('div'); | |
cartItemDiv.classList.add('flex', 'items-center', 'border', 'border-gray-300', 'rounded-md', 'p-4'); | |
cartItemDiv.innerHTML = ` | |
<img src="${product.image}" alt="Product Image" class="w-24 h-24 mr-4"> | |
<div> | |
<h2 class="text-lg font-bold">${product.title}</h2> | |
<p class="text-gray-600">$${product.price.toFixed(2)}</p> | |
<div class="flex items-center mt-2"> | |
<button class="bg-gray-200 px-2 py-1 rounded-md decrease-quantity" data-product-id="${product.id}">-</button> | |
<input type="number" value="${item.quantity}" class="w-16 text-center border border-gray-300 rounded-md mx-2 quantity-input" data-product-id="${product.id}"> | |
<button class="bg-gray-200 px-2 py-1 rounded-md increase-quantity" data-product-id="${product.id}">+</button> | |
<button class="text-red-500 hover:text-red-700 ml-4 remove-item" data-product-id="${product.id}">Remove</button> | |
</div> | |
</div> | |
`; | |
cartItemsContainer.appendChild(cartItemDiv); | |
}); | |
// Add event listeners to quantity buttons and remove buttons | |
const decreaseButtons = document.querySelectorAll('.decrease-quantity'); | |
decreaseButtons.forEach(button => { | |
button.addEventListener('click', function() { | |
const productId = this.dataset.productId; | |
const quantityInput = this.parentNode.querySelector('.quantity-input'); | |
let quantity = parseInt(quantityInput.value); | |
quantity = Math.max(1, quantity - 1); // Ensure quantity is not less than 1 | |
quantityInput.value = quantity; | |
updateQuantity(productId, quantity); | |
}); | |
}); | |
const increaseButtons = document.querySelectorAll('.increase-quantity'); | |
increaseButtons.forEach(button => { | |
button.addEventListener('click', function() { | |
const productId = this.dataset.productId; | |
const quantityInput = this.parentNode.querySelector('.quantity-input'); | |
let quantity = parseInt(quantityInput.value); | |
quantity++; | |
quantityInput.value = quantity; | |
updateQuantity(productId, quantity); | |
}); | |
}); | |
const removeButtons = document.querySelectorAll('.remove-item'); | |
removeButtons.forEach(button => { | |
button.addEventListener('click', function() { | |
const productId = this.dataset.productId; | |
removeItem(productId); | |
}); | |
}); | |
} | |
} | |
// Function to update the order summary in cart.html and checkout.html | |
function updateOrderSummary() { | |
const { subtotal, shipping, total } = calculateTotals(); | |
const subtotalElements = document.querySelectorAll('#subtotal'); | |
subtotalElements.forEach(element => element.textContent = `$${subtotal.toFixed(2)}`); | |
const shippingElements = document.querySelectorAll('#shipping'); | |
shippingElements.forEach(element => element.textContent = `$${shipping.toFixed(2)}`); | |
const totalElements = document.querySelectorAll('#total'); | |
totalElements.forEach(element => element.textContent = `$${total.toFixed(2)}`); | |
} | |
// Function to handle checkout | |
function handleCheckout() { | |
const checkoutForm = document.getElementById('checkout-form'); | |
if (checkoutForm) { | |
checkoutForm.addEventListener('submit', function(event) { | |
event.preventDefault(); // Prevent form submission | |
// Simulate order processing | |
const orderId = Math.floor(Math.random() * 1000000); | |
// Store order ID in local storage | |
localStorage.setItem('orderId', orderId); | |
// Clear the cart | |
setCartItems([]); | |
// Redirect to confirmation page | |
window.location.href = '/confirmation.html'; | |
}); | |
} | |
} | |
// Function to display order confirmation details | |
function displayOrderConfirmation() { | |
const orderId = localStorage.getItem('orderId'); | |
const orderIdElement = document.getElementById('order-id'); | |
if (orderIdElement) { | |
orderIdElement.textContent = orderId; | |
} | |
} | |
document.addEventListener('DOMContentLoaded', function() { | |
// Initialize the cart page | |
if (window.location.pathname === '/cart.html') { | |
displayCartItems(); | |
updateOrderSummary(); | |
} | |
// Initialize the checkout page | |
if (window.location.pathname === '/checkout.html') { | |
updateOrderSummary(); | |
handleCheckout(); | |
} | |
// Initialize the confirmation page | |
if (window.location.pathname === '/confirmation.html') { | |
displayOrderConfirmation(); | |
} | |
}); | |