<!DOCTYPE html>
<html>
<head>
<title>Simple JS Cart</title>
</head>
<body>
<h2>Products</h2>
<div>
<button onclick="addToCart('Apple', 1.00)">Add Apple ($1)</button>
<button onclick="addToCart('Banana', 0.50)">Add Banana ($0.50)</button>
<button onclick="addToCart('Orange', 0.80)">Add Orange ($0.80)</button>
</div>
<h2>Your Cart</h2>
<ul id="cart-list"></ul>
<p><strong>Total: $<span id="total">0.00</span></strong></p>
<script src="cart.js"></script>
</body>
</html>
// Create an empty array to store cart items
let cart = [];
// Function that runs when a product is added to the cart
function addToCart(name, price) {
// Search the cart for an item with the same name
// `i` represents each item while looping through the array
const item = cart.find(i => i.name === name);
// If the item already exists in the cart
if (item) {
// Increase its quantity by 1
item.qty++;
} else {
// Otherwise, add a brand new item object to the cart
cart.push({ name, price, qty: 1 });
}
// Update the cart display on the webpage
updateCart();
}
// Function to refresh and show the current cart items
function updateCart() {
// Get the HTML <ul> element where items will be displayed
const list = document.getElementById("cart-list");
// Get the HTML <span> where the total price will appear
const totalEl = document.getElementById("total");
// Clear the previous cart display
list.innerHTML = "";
// Start total price at 0
let total = 0;
// Loop through all items in the cart
cart.forEach(item => {
// Add this item's total cost (price × quantity) to the total
total += item.price * item.qty;
// Create a new list item <li> for this cart entry
const li = document.createElement("li");
// Set the text, e.g. "Apple x 2 - $2.00"
li.textContent = `${item.name} x ${item.qty} - $${(item.price * item.qty).toFixed(2)}`;
// Add this <li> to the <ul> list
list.appendChild(li);
});
// Update the total price on screen
totalEl.textContent = total.toFixed(2);
}