-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
169 lines (141 loc) · 6.2 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
let container = document.querySelector(".container");
let search = document.querySelector("#search");
let load = 0;
let productsPerPage = 10;
let products = []; // Store all products here
//! Fetch all products initially ------------------------------------------------------------------
async function fetchData() {
let response = await fetch("https://dummyjson.com/products");
let data = await response.json();
products = data.products;
console.log(products);
showData(); // Display the first set of products
}
//! Show a set of products based on the current load count -----------------------------------------
function showData() {
for (let i = load; i < load + productsPerPage && i < products.length; i++) {
let ele = products[i];
let image = document.createElement('img');
image.setAttribute('id','image');
let title = document.createElement('h3');
title.setAttribute('id','title');
let price = document.createElement('p');
price.setAttribute('id','price');
let addtoCart = document.createElement('button');
addtoCart.setAttribute('id','addtoCart');
addtoCart.setAttribute('class','fas fa-cart-plus');
// addtoCart.setAttribute('class',ele.title);
addtoCart.innerText = ' Add to Cart';
// addtoCart.addEventListener('click', addCart)
let slide = document.createElement('div');
slide.addEventListener('click', showDetails);
slide.setAttribute('id','slide');
image.setAttribute('src', ele.images[0]);
title.innerText = ele.title;
price.innerText = '$' + ele.price;
slide.append(image, title, price, addtoCart);
container.append(slide);
}
load += productsPerPage;
checkLoadMore();
}
//! Check if there are more products to load and display the "Load More" button -----------------------
function checkLoadMore() {
let loadButton = document.getElementById('loadButton');
if (load < products.length) {
if (!loadButton) {
loadButton = document.createElement('button');
loadButton.setAttribute('id', 'loadButton');
loadButton.setAttribute('class',"fas fa-spinner fa-spin")
loadButton.innerText = ' Load More';
loadButton.addEventListener('click', showData);
container.append(loadButton);
} else {
container.appendChild(loadButton); // Re-append to maintain position
}
} else if (loadButton) {
loadButton.remove(); // Remove the button if all products are loaded
}
}
//! Add products on cart -----------------------------------------------------------------------------
// function addCart(event){
// let product = event.target.parentNode;
// console.log(product);
// // alert("Item added successfully");
// event.stopPropagation();
// let productString = product.outerHTML;
// localStorage.setItem('product', productString);
// // let productClass = event.target.className;
// // console.log(productClass);
// }
// Existing "Add to Cart" functionality
// Add to Cart logic in script.js
document.addEventListener('click', function(event) {
if (event.target && event.target.id === 'addtoCart') {
const productIndex = Array.from(container.children).indexOf(event.target.closest('#slide'));
const product = products[productIndex];
const cartItems = JSON.parse(localStorage.getItem('cart')) || [];
const existingProduct = cartItems.find(item => item.id === product.id);
if (existingProduct) {
existingProduct.quantity++;
} else {
cartItems.push({
id: product.id,
name: product.title,
price: product.price,
images: product.images, // Ensure the image array is included
quantity: 1
});
}
localStorage.setItem('cart', JSON.stringify(cartItems));
alert(`${product.title} added to cart!`);
}
});
//! show details of any products -----------------------------------------------------------------------
function showDetails(event) {
// Get the clicked product
const slide = event.currentTarget; // The clicked slide
const productIndex = Array.from(container.children).indexOf(slide); // Find the index of the clicked product
const product = products[productIndex]; // Get the product details
// Redirect to product-details.html with the product ID
window.location.href = `Product/product-details.html?id=${product.id}`;
}
//! Search any product ---------------------------------------------------------------------------------
search.addEventListener('keyup',searchProducts);
async function searchProducts() {
let value = search.value;
// console.log(value);
let res = await fetch(`https://dummyjson.com/products/search?q=${value}`);
let searchResult = await res.json();
console.log(searchResult);
container.innerHTML = '';
searchResult.products.forEach((ele)=>{
let image = document.createElement('img');
image.setAttribute('id','image');
let title = document.createElement('h3');
title.setAttribute('id','title');
let price = document.createElement('p');
price.setAttribute('id','price');
let addtoCart = document.createElement('button');
addtoCart.setAttribute('id','addtoCart');
addtoCart.setAttribute('class','fas fa-cart-plus');
addtoCart.innerText = ' Add to Cart';
// addtoCart.addEventListener('click', addCart)
let slide = document.createElement('div');
slide.addEventListener('click', showDetails);
slide.setAttribute('id','slide');
image.setAttribute('src', ele.images[0]);
title.innerText = ele.title;
price.innerText = '$' + ele.price;
slide.append(image, title, price, addtoCart);
container.append(slide);
})
if (searchResult.products.length === 0) {
let noResultMessage = document.createElement('h1');
noResultMessage.innerText = 'No Products Found';
noResultMessage.style.color = 'red';
noResultMessage.style.padding = '100px'
container.append(noResultMessage);
}
}
fetchData();