diff --git a/assets/js/main.js b/assets/js/main.js new file mode 100644 index 0000000..1c62743 --- /dev/null +++ b/assets/js/main.js @@ -0,0 +1,155 @@ +// Smooth scrolling for anchor links +document.querySelectorAll('a[href^="#"]').forEach(anchor => { + anchor.addEventListener('click', function (e) { + e.preventDefault(); + document.querySelector(this.getAttribute('href')).scrollIntoView({ + behavior: 'smooth' + }); + }); +}); + +function addToCart(name, price, quantityId) { + const quantityInput = document.getElementById(quantityId); + const quantity = parseInt(quantityInput.value, 10); + + if (quantity < 1) { + alert("Quantity must be at least 1."); + return; + } + + let cart = JSON.parse(localStorage.getItem('cart')) || {}; + if (cart[name]) { + cart[name].quantity += quantity; + } else { + cart[name] = { + price: price, + quantity: quantity + }; + } + localStorage.setItem('cart', JSON.stringify(cart)); + updateCartCount(); + updateButtonStates(); +} + +function updateCartCount() { + let cart = JSON.parse(localStorage.getItem('cart')) || {}; + let count = Object.values(cart).reduce((sum, item) => sum + item.quantity, 0); + const cartCountElement = document.getElementById('cart-count'); + if (cartCountElement) { + cartCountElement.innerText = count; + } +} + +function updateButtonStates() { + let cart = JSON.parse(localStorage.getItem('cart')) || {}; + const buttons = document.querySelectorAll('.buy-button'); + buttons.forEach(button => { + const productName = button.getAttribute('data-product-name'); + if (cart[productName]) { + button.textContent = 'In the cart'; + button.disabled = true; + } else { + button.textContent = 'Buy'; + button.disabled = false; + } + }); +} + +function renderCart() { + const cartContainer = document.getElementById('cart-container'); + if (!cartContainer) return; + + let cart = JSON.parse(localStorage.getItem('cart')) || {}; + + if (Object.keys(cart).length === 0) { + cartContainer.innerHTML = ` +
Your cart is currently empty.
+ Continue Shopping +| Item | +Price | +Quantity | +Total | ++ |
|---|---|---|---|---|
| ${name} | +${item.price.toFixed(2)} | ++ + | +${total.toFixed(2)} | ++ |