-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (73 loc) · 2.58 KB
/
index.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
"use strict";
function setActiveCategory(nextCategory) {
// Setting active class to next category
const categoryElems = document.querySelectorAll(".category");
for (let categoryElem of categoryElems) {
if (
categoryElem.attributes.getNamedItem("data-value").value ===
nextCategory
) {
categoryElem.classList.add("active");
generateProducts(nextCategory);
} else {
categoryElem.classList.remove("active");
}
}
}
function setCategories() {
// Adding event listeners to change class, and products
const categoryElems = document.querySelectorAll(".category");
for (let categoryElem of categoryElems) {
categoryElem.addEventListener("click", () => {
setActiveCategory(
categoryElem.attributes.getNamedItem("data-value").value
);
});
}
}
function generateCartBtns(productId) {
let quantity = 0;
let product = cart.find((prod) => prod.id === productId);
if (product) {
quantity = product.quantity;
}
let btnElem = Object.assign(document.createElement("div"), {
className: `quantity ${quantity ? "" : "quantity-1"}`,
innerHTML: quantity
? `<button onclick="removeFromCart(${productId})">−</button>
<p>${quantity}</p>
<button onclick="addToCart(${productId})">+</button>`
: `<button onclick="addToCart(${productId})">Add to cart</button>`,
});
return btnElem;
}
function generateProducts(category = "all") {
const productsSection = document.querySelector("#products-section");
// Removing existing products
while (productsSection.childElementCount) {
let child = productsSection.children[0];
productsSection.removeChild(child);
}
// Generating product based on category
for (let product of PRODUCTS) {
if (category !== "all" && category !== product.category) continue;
let childElem = Object.assign(document.createElement("div"), {
className: "product",
id: product.id,
innerHTML: `
<div class="product-img">
<img src="./assets/products/${product.name}.png" alt="${product.name}" />
</div>
<h2>${product.name}</h2>
<p>₹ ${product.rate}</p>
`,
});
childElem.appendChild(generateCartBtns(product.id));
productsSection.appendChild(childElem);
}
}
function main() {
generateProducts("all");
setCategories();
}
main();