-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript-search.js
More file actions
354 lines (305 loc) · 10.9 KB
/
script-search.js
File metadata and controls
354 lines (305 loc) · 10.9 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
(function() {
const productsContainer = document.querySelector("#grid");
const cartContainer = document.querySelector("#shopping-cart");
const cartContent = document.querySelector("#cart-content");
const toggleCartBtn = document.querySelector("#toggle-cart-btn");
const clearCartBtn = document.querySelector("#clear-cart");
const checkoutBtn = document.querySelector("#checkout-btn");
const totalPriceContainer = document.querySelector("#total-price");
window.onload = () => {
filterProduct("All");
};
// FUNCTIONS
function toggleCart() {
// toggle shopping cart visibility
cartContainer.classList.toggle("open");
}
function getLSContent() {
// get contents from local storage.
// if nothing is there, create an empty array
const lsContent = JSON.parse(localStorage.getItem("products")) || [];
return lsContent;
}
function setLSContent(lsContent) {
// save content inside local storage
localStorage.setItem("products", JSON.stringify(lsContent));
}
function calculateTotal(prices) {
// calculate the total price in the cart
return prices.reduce(function(prev, next) {
return prev + next;
}, 0);
}
function getCartItemPrices() {
// extract the price numbers from the cart items to calculate total
const prices = [];
// retrieve the td element in the cart where the product price is stored
// for each product in the cart
let nums = cartContent.querySelectorAll("tr td:nth-child(3)");
// iterate over each td node and extract the price
// strip the £ sign from the text, turn the string into
// a number and push the number into the prices array
if (nums.length > 0) {
for (let cell = 0; cell < nums.length; cell++) {
let num = nums[cell].innerText;
num = num.replace(/[^\d]/g, "");
num = parseFloat(num);
prices.push(num);
}
// return the prices array
return prices;
} else {
return;
}
}
function displayCartTotal() {
// display the total cost in the cart
const prices = getCartItemPrices();
let total = 0;
if (prices) {
total = calculateTotal(prices);
totalPriceContainer.innerHTML = `<span class="total">Total: £ ${total/100}</span>`;
} else {
totalPriceContainer.innerHTML = '<span class="total">Total: £ 0.00</span>';
}
}
function displayProducts() {
// display all products in the cart
// get contents from local storage
const lsContent = getLSContent();
let productMarkup = "";
// if local storage is not empty, build the
// cart items markup and the appropriate details
if (lsContent !== null) {
for (let product of lsContent) {
productMarkup += `
<tr>
<td><img class="cart-image" src="${product.image}" alt="${
product.name
}" width="120"></td>
<td>
${product.name}
</td>
<td>${product.price}</td>
<td><a href="#" data-id="${product.id}" class="remove">X</a></td>
</tr>
`;
}
} else {
// if no content is in local storage, alert user
productMarkup = "Your cart is empty.";
}
// add markup to DOM
cartContent.querySelector("tbody").innerHTML = productMarkup;
}
function saveProduct(clickedBtn) {
// save selected product in local storage and display it in the cart together
// vars
const productId = clickedBtn.getAttribute("data-id");
const card = clickedBtn.parentElement.parentElement;
const cardInfo = clickedBtn.parentElement;
const prodImage = cardInfo.querySelector(".card__image").src;
const prodName = cardInfo.querySelector(".card__title").textContent;
const prodPrice = cardInfo.querySelector(".card__price").textContent;
let isProductInCart = false;
// get local storage array
const lsContent = getLSContent();
// to avoid user adds the same course twice, check
// the product is not in LS already before adding it
lsContent.forEach(function(product) {
if (product.id === productId) {
alert("This movie is already in your cart.");
isProductInCart = false;
}
});
// only if the product is not already in the cart,
// create an object representing selected product info
// and push it into local storage array
if (!isProductInCart) {
lsContent.push({
id: productId,
image: prodImage,
name: prodName,
price: prodPrice
});
// add product into into local storage
setLSContent(lsContent);
// update the display of courses in the shopping cart
displayProducts();
}
}
function removeProduct(productId) {
// remove product from cart (and from local storage)
// retrieve list of products from LS
const lsContent = getLSContent();
// get the index of the product item to remove
// inside the local storage content array
let productIndex;
lsContent.forEach(function(product, i) {
if (product.id === productId) {
productIndex = i;
}
});
// modify the items in local storage array
// to remove the selected product item
lsContent.splice(productIndex, 1);
// update local storage content
setLSContent(lsContent);
displayProducts();
}
function clearCart() {
// clear all products from cart (and local storage)
// retrieve list of products from LS
const lsContent = getLSContent();
// empty array in local storage
lsContent.splice(0, lsContent.length);
// update local storage
setLSContent(lsContent);
// display cart content again
displayProducts();
}
function checkout() {
// checkout: just clear the cart
// after user confirms the checkout process
const cartProducts = cartContent.querySelector("tbody").innerHTML;
if (cartProducts !== "" && confirm("Are you sure you want to checkout?")) {
clearCart();
} else {
return;
}
}
// BIND EVENTS AND CALL FUNCTIONS
// Page load:
document.addEventListener("DOMContentLoaded", function(e) {
// display list of products in cart, if any, on page load
displayProducts();
// display cart total
displayCartTotal();
});
// open and close shopping cart
// when cart button is clicked
toggleCartBtn.addEventListener("click", function(e) {
e.preventDefault();
toggleCart();
});
// Save product in cart and Local Storage
// when add to cart button is clicked
productsContainer.addEventListener("click", function(e) {
if (e.target.classList.contains("add-to-cart")) {
e.preventDefault();
const clickedBtn = e.target;
saveProduct(clickedBtn);
}
});
productsContainer.addEventListener("click", function(e) {
if (e.target.classList.contains("add-to-cart")) {
displayCartTotal();
}
});
// bind removeProduct to click event of the cartContent table
cartContent.querySelector("tbody").addEventListener("click", function(e) {
e.preventDefault();
// identify the button that was clicked
const clickedBtn = e.target;
// if it's a remove button
if (e.target.classList.contains("remove")) {
// get the value of the data-id property, which contains the
// id of the selected product
const productId = clickedBtn.getAttribute("data-id");
// use the id to remove the selected product
removeProduct(productId);
// display products in the cart again,
// now the list should be displayed with 1 less product
// or empty if no products are left in the cart
// adjust the total
displayCartTotal();
}
});
// bind the button to clear the cart both to the function that
// clears the cart and to the function that adjusts the total price
clearCartBtn.addEventListener("click", function(e) {
e.preventDefault();
clearCart();
});
clearCartBtn.addEventListener("click", displayCartTotal);
// bind the button that does the checkout both to the function that
// controls the checkout and and to the function that adjusts the total price
checkoutBtn.addEventListener("click", function(e) {
e.preventDefault();
checkout();
});
checkoutBtn.addEventListener("click", displayCartTotal);
})();
/*get data from json file */
let http = new XMLHttpRequest();
http.open('get', 'products.json', true);
http.send();
http.onload = function(){
if(this.readyState == 4 && this.status == 200){
let products__movies = JSON.parse(this.responseText).reverse();
let output = "";
for(let item of products__movies){
output += `
<div class="product-movies ${item.Genres} hide">
<img src="${item.image}" class="card__image" alt="${item.description}">
<p class="card__title ${item.Title}">${item.Title.toUpperCase()}</p>
<p class="description card__text"><span><strong>Run time/Year/Dir.:</strong> </span><span>${item.description}</span></p>
<p class="description"><span>Genres: </span> <span>${item.Genres} </span></p>
<p class="card__price">
<span>£</span>
<span>${item.price}</span>
</p>
<button class="card__btn add-to-cart" data-id="${item.id}">Add to cart </button>
<p class="stock-level"><span>Stock Level: </span> <span>${item.stock}</span></p>
</div>
`;
}
document.querySelector(".products__movies").innerHTML = output;
}
}
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value == button.innerText) {
button.classList.add("active");
} else {
button.classList.remove("active");
}
});
let elements = document.querySelectorAll(".product-movies");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "All") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
element.classList.add("hide");
}
}
});
}
document.getElementById("search").addEventListener("click", () => {
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".card__title");
let cards = document.querySelectorAll(".product-movies");
//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
cards[index].classList.add("hide");
}
});
});