Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created April 12, 2025 12:49
Show Gist options
  • Save thinkphp/95cda3d4699259ca1f12dd422803894b to your computer and use it in GitHub Desktop.
Save thinkphp/95cda3d4699259ca1f12dd422803894b to your computer and use it in GitHub Desktop.
Order-coffee-javascript
<script>
// Coffee products data
const coffeeProducts = [
{
id: 1,
name: "Espresso",
price: 2.99,
description: "Strong and concentrated coffee shot"
},
{
id: 2,
name: "Cappuccino",
price: 4.50,
description: "Espresso with steamed milk and foam"
},
{
id: 3,
name: "Latte",
price: 4.99,
description: "Espresso with a lot of steamed milk"
},
{
id: 4,
name: "Americano",
price: 3.50,
description: "Espresso diluted with hot water"
},
{
id: 5,
name: "Mocha",
price: 5.50,
description: "Espresso with chocolate and steamed milk"
},
{
id: 6,
name: "Macchiato",
price: 3.99,
description: "Espresso with a dollop of milk foam"
}
];
// Shopping cart array
let cart = [];
// DOM elements
const productsContainer = document.getElementById('products-container');
const cartItemsContainer = document.getElementById('cart-items');
const cartTotalElement = document.getElementById('cart-total');
const checkoutButton = document.getElementById('checkout-button');
const emptyCartButton = document.getElementById('emptycart-button');
const notification = document.getElementById('notification');
// Display products
function displayProducts() {
productsContainer.innerHTML = '';
coffeeProducts.forEach(product => {
const productCard = document.createElement('div');
productCard.className = 'product-card';
productCard.innerHTML = `
<div class="product-image">Coffee Image: ${product.name}</div>
<div class="product-info">
<h3 class="product-title">${product.name}</h3>
<div class="product-price">$${product.price.toFixed(2)}</div>
<div class="product-description">${product.description}</div>
<button class="add-to-cart-button" data-id="${product.id}">Add to Cart</button>
</div>
`;
productsContainer.appendChild(productCard);
});
// Add event listeners to all "Add to Cart" buttons
document.querySelectorAll('.add-to-cart-button').forEach(button => {
button.addEventListener('click', addToCart);
});
}
// Add to cart function
function addToCart(event) {
const productId = parseInt(event.target.getAttribute('data-id'));
const product = coffeeProducts.find(p => p.id === productId);
// Check if the product already exists in the cart
const existingItem = cart.find(item => item.id === productId);
if (existingItem) {
existingItem.quantity += 1;
} else {
cart.push({
id: product.id,
name: product.name,
price: product.price,
quantity: 1
});
}
// Show notification
showNotification(`Added ${product.name} to cart!`);
// Update cart display
updateCart();
}
// Update cart display
function updateCart() {
if (cart.length === 0) {
cartItemsContainer.innerHTML = '<p class="empty-cart-message">Your cart is empty</p>';
checkoutButton.disabled = true;
emptyCartButton.disabled = true;
} else {
cartItemsContainer.innerHTML = '';
cart.forEach(item => {
const cartItem = document.createElement('div');
cartItem.className = 'cart-item';
cartItem.innerHTML = `
<div class="item-info">
<h3 class="item-title">${item.name}</h3>
<div class="item-price">$${item.price.toFixed(2)} each</div>
</div>
<div class="item-controls">
<button class="decrease-quantity" data-id="${item.id}">-</button>
<span class="item-quantity">${item.quantity}</span>
<button class="increase-quantity" data-id="${item.id}">+</button>
<button class="remove-item" data-id="${item.id}" style="margin-left: 10px; background-color: #f44336;">×</button>
</div>
`;
cartItemsContainer.appendChild(cartItem);
});
checkoutButton.disabled = false;
emptyCartButton.disabled = false;
}
// Calculate and update the cart total
updateCartTotal();
// Add event listeners to quantity buttons
document.querySelectorAll('.decrease-quantity').forEach(button => {
button.addEventListener('click', decreaseQuantity);
});
document.querySelectorAll('.increase-quantity').forEach(button => {
button.addEventListener('click', increaseQuantity);
});
document.querySelectorAll('.remove-item').forEach(button => {
button.addEventListener('click', removeItem);
});
}
// Update cart total
function updateCartTotal() {
const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
cartTotalElement.textContent = `Total: $${total.toFixed(2)}`;
}
// Increase item quantity
function increaseQuantity(event) {
const productId = parseInt(event.target.getAttribute('data-id'));
const item = cart.find(item => item.id === productId);
if (item) {
item.quantity += 1;
updateCart();
}
}
// Decrease item quantity
function decreaseQuantity(event) {
const productId = parseInt(event.target.getAttribute('data-id'));
const item = cart.find(item => item.id === productId);
if (item) {
item.quantity -= 1;
if (item.quantity <= 0) {
removeItem(event);
} else {
updateCart();
}
}
}
// Remove item from cart
function removeItem(event) {
const productId = parseInt(event.target.getAttribute('data-id'));
cart = cart.filter(item => item.id !== productId);
updateCart();
}
// Empty the cart
function emptyCart() {
cart = [];
updateCart();
showNotification('Cart has been emptied');
}
// Show notification
function showNotification(message) {
notification.textContent = message;
notification.classList.add('show');
setTimeout(() => {
notification.classList.remove('show');
}, 3000);
}
// Checkout function
function checkout() {
// In a real application, this would connect to a payment processor
alert(`Proceeding to checkout with ${cart.length} items. Total: $${calculateTotal().toFixed(2)}`);
cart = [];
updateCart();
showNotification('Thank you for your order!');
}
// Calculate total function (for checkout)
function calculateTotal() {
return cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
// Initialize the application
function init() {
// Display products
displayProducts();
// Initial cart update
updateCart();
// Add event listeners for checkout and empty cart buttons
checkoutButton.addEventListener('click', checkout);
emptyCartButton.addEventListener('click', emptyCart);
}
// Start the application when DOM is fully loaded
document.addEventListener('DOMContentLoaded', init);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment