`To make this work across multiple pages (products page + cart page) using an external JS file, you mainly need to:
Keep using localStorage (you already are ✅)
Move your JS into a separate file
Make sure both pages include that script
Pass product data from your SQL-loaded HTML into addToCart()
✅ 1. Create external JS file
static/js/cart.js
let cart = JSON.parse(localStorage.getItem('cart')) || [];
function saveCart() {
localStorage.setItem('cart', JSON.stringify(cart));
}
function addToCart(id, name, price) {
const existing = cart.find(item => item.id === id);
if (existing) {
existing.qty += 1;
} else {
cart.push({ id, name, price, qty: 1 });
}
saveCart();
renderCart();
}
function removeFromCart(id) {
cart = cart.filter(item => item.id !== id);
saveCart();
renderCart();
}
function renderCart() {
const cartBox = document.getElementById('cart-items');
const totalBox = document.getElementById('cart-total');
if (!cartBox || !totalBox) return; // IMPORTANT (prevents errors on other pages)
cartBox.innerHTML = '';
let total = 0;
cart.forEach(item => {
total += item.price * item.qty;
const div = document.createElement('div');
div.className = 'cart-item';
div.innerHTML = `
<span>${item.name} x${item.qty}</span>
<span>£${(item.price * item.qty).toFixed(2)}</span>
<button onclick="removeFromCart(${item.id})">✕</button>
`;
cartBox.appendChild(div);
});
totalBox.innerText = 'Total: £' + total.toFixed(2);
}
document.addEventListener('DOMContentLoaded', renderCart);
✅ 2. Include it on BOTH pages
Products page:
Cart page:
✅ 3. Products page (data from SQL)
In your Flask route:
products = q("SELECT * FROM products")
return render_template("products.html", products=products)
In your products.html
{% for p in products %}
<p>{{ p.name }} - £{{ p.price }}</p>
Add to Cart
{% endfor %}
⚠️ Important fix (very important)
If product names can have quotes, use this safer version:
✅ 4. Cart page
Your Cart
<h3 id="cart-total">Total: £0.00</h3>
✅ How it works now
Products page → adds items to localStorage
Cart page → reads same localStorage
renderCart() runs on both pages
No backend needed for cart (yet)
🔥 Optional upgrades (tell me if you want)
Quantity +/- buttons
Persist cart to database (for logged-in users)
Cart icon with item count
Stripe checkout
If something doesn’t work, it’s usually one of these:
Wrong script path (/static/js/cart.js)
Missing tojson filter
IDs not matching
Paste your HTML if you want me to debug it directly.`
Top comments (0)