-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
60 lines (51 loc) · 1.53 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
const companyList = document.querySelector(".nav>ul");
const productsContainer = document.querySelector(".products");
const input = document.querySelector(".nav>input");
let filteredProducts = [...products];
const displayCompanies = () => {
const buttons = [
"all",
...new Set(products.map((product) => product.company)),
];
companyList.innerHTML = buttons
.map((company) => {
return `<li data-id="${company}">${company}</li>`;
})
.join("");
};
displayCompanies();
const displayProducts = () => {
if (filteredProducts.length < 1) {
productsContainer.innerHTML = `<h4>Sorry, no products matched your search</h4>`;
return;
}
productsContainer.innerHTML = filteredProducts
.map((item) => {
return `
<article class="product">
<img src=${item.image} alt=${item.title} />
<h5 class="product-name">${item.title}</h5>
<span class="product-price">$${item.price}</span>
</article>`;
})
.join("");
};
displayProducts();
input.addEventListener("keyup", (e) => {
let searchVal = input.value;
filteredProducts = products.filter((item) => {
return item.title.toLowerCase().includes(searchVal);
});
displayProducts();
});
companyList.addEventListener("click", (e) => {
let btnTarget = e.target.dataset.id;
if (btnTarget === "all") {
filteredProducts = [...products];
displayProducts();
} else {
filteredProducts = products.filter((item) => item.company === btnTarget);
displayProducts();
}
input.value = "";
});