-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
96 lines (86 loc) · 2.85 KB
/
app.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const productsContainer = document.querySelector("#products-container");
const basketTotalContainer = document.querySelector("#totals-container");
const renderBasket = () => {
productsContainer.innerHTML = '';
products.forEach(product => {
productsContainer.innerHTML += `
<div class="basket-item-outer-container">
<img src=${product.imgSrc} alt=${product.name}>
<div class="basket-item-inner-container">
<div class="basket-item-info">
<h2>${product.name}</h2>
<p>$${product.discountPrice} <span>$${product.oldPrice}</span></p>
</div>
<div class="basket-item-quantity">
<button onclick="changeQuantity('minus', ${product.id})" id="decrement">−</button>
<h2 id="quantity">${product.quantity}</h2>
<button onclick="changeQuantity('plus', ${product.id})" id="increment">+</button>
</div>
</div>
</div>
`;
});
};
renderBasket();
const changeQuantity = (action, id) => {
products.map(product => {
if(product.id === id){
if(product.quantity > 0 && action === 'minus'){
product.quantity-=1;
}
else if(action === 'plus'){
product.quantity+=1;
}
if(product.quantity === 0){
removeItemFromCart(product.id);
}
updateCart();
return {...product, quantity: product.quantity};
};
});
};
const basketTotal = () => {
let totalPrice = 0, totalShipping = 0;
products.forEach(product => {
totalPrice += product.discountPrice * product.quantity;
totalShipping += product.shipping * product.quantity;
});
if(totalShipping >= 500){
basketTotalContainer.innerHTML = `
<div id="shipping">
<h2>Free Shipping! 🥳</h2>
</div>
<div id="total">
<h2>Total</h2>
<p>$${totalPrice.toFixed(2)}</p>
</div>
`;
} else if (totalShipping < 500){
basketTotalContainer.innerHTML = `
<div id="shipping">
<h2>Shipping</h2>
<p>$${totalShipping}</p>
</div>
<div id="total">
<h2>Total</h2>
<p>$${totalPrice.toFixed(2)}</p>
</div>
`;
};
if(totalPrice === 0) {
basketTotalContainer.innerHTML = `
<div id="empty-basket-message-container">
<h2>Your basket is empty! 🛒<h2> <p>Please refresh your web browser to refill your basket.</p>
</div>
`
};
};
basketTotal();
const updateCart = () => {
renderBasket();
basketTotal();
};
const removeItemFromCart = (id) => {
products = products.filter(product => product.id !== id);
updateCart();
};