-
Notifications
You must be signed in to change notification settings - Fork 0
/
global-script.js
83 lines (71 loc) · 2.23 KB
/
global-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
"use strict";
let cart = [];
function setToggleMenu() {
const menuIcon = document.querySelector("#menu-icon");
const imgIcon = document.querySelector("#menu-icon img");
const navSection = document.querySelector("#nav-section");
menuIcon.addEventListener("click", () => {
let imgPath = imgIcon.getAttribute("src");
let isActive = imgPath.includes("close");
imgPath = isActive
? imgPath.replace("close", "menu")
: imgPath.replace("menu", "close");
imgIcon.setAttribute("src", imgPath);
let navDisplay = isActive ? "none" : "block";
navSection.setAttribute("style", `display:${navDisplay}`);
});
}
function getCartState() {
cart = JSON.parse(localStorage.getItem("cart"));
if (!cart) {
cart = [];
setCartState();
}
}
function setCartState() {
localStorage.setItem("cart", JSON.stringify(cart));
}
function updateProductCard(productId) {
const productsSection = document.querySelector("#products-section");
for (let product of productsSection.children) {
if (product.id == productId) {
product.children[3].remove();
product.appendChild(generateCartBtns(productId));
return;
}
}
}
function addToCart(productId) {
if (!PRODUCTS.find((prod) => prod.id === productId)) return;
let product = cart.find((prod) => prod.id === productId);
if (product) {
cart = cart.map((prod) =>
prod.id === productId
? { ...prod, quantity: prod.quantity + 1 }
: prod
);
} else {
product = PRODUCTS.find((prod) => prod.id === productId);
cart.push({ ...product, quantity: 1 });
}
setCartState();
updateProductCard(product.id);
}
function removeFromCart(productId) {
if (!PRODUCTS.find((prod) => prod.id === productId)) return;
let product = cart.find((prod) => prod.id === productId);
if (product) {
cart = cart.map((prod) =>
prod.id === productId
? { ...prod, quantity: prod.quantity - 1 }
: prod
);
}
setCartState();
updateProductCard(product.id);
}
function main() {
setToggleMenu();
getCartState();
}
main();