-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
52 lines (45 loc) · 1.8 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {getCart, setCart} from "./util/cart.mjs";
import {renderHeader} from "./util/header.mjs";
import {getProducts, setProducts} from "./util/products.mjs";
const productsPath = 'data/products.json';
renderHeader();
loadProducts();
addEvents();
function addEvents() {
document.getElementById("categories").addEventListener("click", (evt) => renderProducts(evt.target.value));
}
// Fetch data from products.json and store to local storage
function loadProducts() {
fetch(productsPath).then(raw => raw.json()).then(setProducts).then(renderProducts);
}
// render products based on given categories
function renderProducts(cat) {
const productContainer = document.getElementById('products');
productContainer.innerHTML = "";
const products = getProducts();
for (const product of products) {
if (!cat || product.category === cat) {
productContainer.innerHTML += `
<div class="product-item">
<img class="product-image" src="${product.imageURL}" alt="">
<div class="product-data">
<h3 class="product-title">${product.name}</h3>
<div class="product-description">
<h4 class="product-price">${product.price}€</h4>
<button class="product-btn btn" onclick="addToCart('${product.id}')">
Add to cart
</button>
</div>
</div>
</div>`;
}
}
}
// Add the item with the product id to the current user's cart
window.addToCart = function (prodId) {
const cart = getCart();
const index = cart.findIndex(item => item.id === prodId);
if (index === -1) cart.push({id: prodId, count: 1}); else cart[index].count += 1;
setCart(cart);
renderHeader();
}