forked from uzairansari11/Apna-E-Cart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearchedProduct.js
79 lines (69 loc) · 2.45 KB
/
searchedProduct.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
let searchedInput = document.getElementById("searchInput");
let data = JSON.parse(sessionStorage.getItem("searchedData"));
let cartItems =
JSON.parse(localStorage.getItem("apan_e-store_cartproduct")) || [];
if (data.length == 0) {
document.querySelector("#subcontainer").innerHTML = `${alert(
"Sorry No Result Found!!😔"
)}
${(window.location.href = "index.html")}
`;
} else {
function displayCards(data) {
document.querySelector("#subcontainer").innerHTML = "";
data.forEach((element) => {
let div = document.createElement("div");
let img = document.createElement("img");
img.setAttribute("src", element.avatar);
img.addEventListener("click", function () {
localStorage.setItem("product_details", JSON.stringify(element));
window.location.href = "product.html";
});
let discription = document.createElement("p");
let str = element.discription;
discription.innerText = `${str.substring(0, 50)}...`;
let price = document.createElement("h4");
price.innerHTML = `<h4>₹ ${element.price}</h4>`;
let offer = document.createElement("p");
offer.innerText = "OFFER AVAILABLE";
let cart_btn = document.createElement("button");
cart_btn.innerText = "Add To Cart";
cart_btn.addEventListener("click", function () {
if (cartItems.includes(element)) {
alert("Already Existing Item in Cart");
} else {
cartItems.push(element);
localStorage.setItem(
"apan_e-store_cartproduct",
JSON.stringify(cartItems)
);
}
});
div.append(img, discription, price, offer, cart_btn);
// document.querySelector("#subcontainer").style.height+=250
document.querySelector("#subcontainer").append(div);
});
}
displayCards(data);
}
let serachBtn = document.querySelector("#searchBar form");
serachBtn.addEventListener("submit", (event) => {
event.preventDefault();
searchedData(searchInput);
});
async function searchedData(searchedInput) {
let data = await fetch(
`https://63996f3916b0fdad773c979e.mockapi.io/products?filter=${searchedInput.value}`
);
console.log(data);
let renderedData = await data.json();
console.log(renderedData.length);
if (renderedData.length == 0) {
document.querySelector(
"#subcontainer"
).innerHTML = `<h1>Sorry No Result Found!!😔</h1>
`;
} else {
displayCards(renderedData);
}
}