-
Notifications
You must be signed in to change notification settings - Fork 8
/
script.js
242 lines (192 loc) · 5.64 KB
/
script.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
let products = [];
let cart = [];
//* selectors
const selectors = {
products: document.querySelector(".products"),
cartBtn: document.querySelector(".cart-btn"),
cartQty: document.querySelector(".cart-qty"),
cartClose: document.querySelector(".cart-close"),
cart: document.querySelector(".cart"),
cartOverlay: document.querySelector(".cart-overlay"),
cartClear: document.querySelector(".cart-clear"),
cartBody: document.querySelector(".cart-body"),
cartTotal: document.querySelector(".cart-total"),
};
//* event listeners
const setupListeners = () => {
document.addEventListener("DOMContentLoaded", initStore);
// product event
selectors.products.addEventListener("click", addToCart);
// cart events
selectors.cartBtn.addEventListener("click", showCart);
selectors.cartOverlay.addEventListener("click", hideCart);
selectors.cartClose.addEventListener("click", hideCart);
selectors.cartBody.addEventListener("click", updateCart);
selectors.cartClear.addEventListener("click", clearCart);
};
//* event handlers
const initStore = () => {
loadCart();
loadProducts("https://fakestoreapi.com/products")
.then(renderProducts)
.finally(renderCart);
};
const showCart = () => {
selectors.cart.classList.add("show");
selectors.cartOverlay.classList.add("show");
};
const hideCart = () => {
selectors.cart.classList.remove("show");
selectors.cartOverlay.classList.remove("show");
};
const clearCart = () => {
cart = [];
saveCart();
renderCart();
renderProducts();
setTimeout(hideCart, 500);
};
const addToCart = (e) => {
if (e.target.hasAttribute("data-id")) {
const id = parseInt(e.target.dataset.id);
const inCart = cart.find((x) => x.id === id);
if (inCart) {
alert("Item is already in cart.");
return;
}
cart.push({ id, qty: 1 });
saveCart();
renderProducts();
renderCart();
showCart();
}
};
const removeFromCart = (id) => {
cart = cart.filter((x) => x.id !== id);
// if the last item is remove, close the cart
cart.length === 0 && setTimeout(hideCart, 500);
renderProducts();
};
const increaseQty = (id) => {
const item = cart.find((x) => x.id === id);
if (!item) return;
item.qty++;
};
const decreaseQty = (id) => {
const item = cart.find((x) => x.id === id);
if (!item) return;
item.qty--;
if (item.qty === 0) removeFromCart(id);
};
const updateCart = (e) => {
if (e.target.hasAttribute("data-btn")) {
const cartItem = e.target.closest(".cart-item");
const id = parseInt(cartItem.dataset.id);
const btn = e.target.dataset.btn;
btn === "incr" && increaseQty(id);
btn === "decr" && decreaseQty(id);
saveCart();
renderCart();
}
};
const saveCart = () => {
localStorage.setItem("online-store", JSON.stringify(cart));
};
const loadCart = () => {
cart = JSON.parse(localStorage.getItem("online-store")) || [];
};
//* render functions
const renderCart = () => {
// show cart qty in navbar
const cartQty = cart.reduce((sum, item) => {
return sum + item.qty;
}, 0);
selectors.cartQty.textContent = cartQty;
selectors.cartQty.classList.toggle("visible", cartQty);
// show cart total
selectors.cartTotal.textContent = calculateTotal().format();
// show empty cart
if (cart.length === 0) {
selectors.cartBody.innerHTML =
'<div class="cart-empty">Your cart is empty.</div>';
return;
}
// show cart items
selectors.cartBody.innerHTML = cart
.map(({ id, qty }) => {
// get product info of each cart item
const product = products.find((x) => x.id === id);
const { title, image, price } = product;
const amount = price * qty;
return `
<div class="cart-item" data-id="${id}">
<img src="${image}" alt="${title}" />
<div class="cart-item-detail">
<h3>${title}</h3>
<h5>${price.format()}</h5>
<div class="cart-item-amount">
<i class="bi bi-dash-lg" data-btn="decr"></i>
<span class="qty">${qty}</span>
<i class="bi bi-plus-lg" data-btn="incr"></i>
<span class="cart-item-price">
${amount.format()}
</span>
</div>
</div>
</div>`;
})
.join("");
};
const renderProducts = () => {
selectors.products.innerHTML = products
.map((product) => {
const { id, title, image, price } = product;
// check if product is already in cart
const inCart = cart.find((x) => x.id === id);
// make the add to cart button disabled if already in cart
const disabled = inCart ? "disabled" : "";
// change the text if already in cart
const text = inCart ? "Added in Cart" : "Add to Cart";
return `
<div class="product">
<img src="${image}" alt="${title}" />
<h3>${title}</h3>
<h5>${price.format()}</h5>
<button ${disabled} data-id=${id}>${text}</button>
</div>
`;
})
.join("");
};
//* api functions
const loadProducts = async (apiURL) => {
try {
const response = await fetch(apiURL);
if (!response.ok) {
throw new Error(`http error! status=${response.status}`);
}
products = await response.json();
console.log(products);
} catch (error) {
console.error("fetch error:", error);
}
};
//* helper functions
const calculateTotal = () => {
return cart
.map(({ id, qty }) => {
const { price } = products.find((x) => x.id === id);
return qty * price;
})
.reduce((sum, number) => {
return sum + number;
}, 0);
};
Number.prototype.format = function () {
return this.toLocaleString("en-US", {
style: "currency",
currency: "USD",
});
};
//* initialize
setupListeners();