-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart.js
437 lines (357 loc) · 15.6 KB
/
cart.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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
let item;
const container = document.getElementById('container');
document.addEventListener('DOMContentLoaded', fetchData);
fetch('navigation.html')
.then(response => response.text())
.then(data => {
// Insert the navigation code into the placeholder div
document.getElementById('navigation-placeholder').innerHTML = data;
$('#openCart').remove();
const parentContainer = document.getElementById('navigation-placeholder');
parentContainer.addEventListener('click', function (event) {
// Check if the clicked element matches the desired selector
/* if (event.target.matches('.button__badge')) {
// Handle the event for the dynamically created element
window.location.href = './cart.html'
} */
});
const jsonArray = JSON.parse(localStorage.getItem('IDs'));
$('.button__badge').text(jsonArray.length)
$('.website-name').click(function () {
window.location.href = "./home.html";
})
$('#openCart').click(function () {
window.location.href = "./cart.html"
})
$('#search-button').on('click', function () {
if ($('#search-input').val()) {
window.location.href = "./search.html?search="+$('#search-input').val();
}
});
});
fetch('./footer.html')
.then(response => response.text())
.then(data => {
// Insert the navigation code into the placeholder div
document.getElementById('footer-placeholder').innerHTML = data;
});
let jsonData;
async function fetchData() {
const apiUrl = 'https://ahmetozydn.github.io/api/products.json'; // url to fetch data
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Network response was not ok.');
}
console.log(response);
jsonData = await response.json(); // JSON data is fetched
const jsonArray = JSON.parse(localStorage.getItem('IDs')); // find if of all products in the cart
jsonData.forEach(item =>{
jsonArray.forEach(element =>{
if(element == item.id){ // id comparison to find details of products
// assign values dynamically with JQuery
let productDetail = `<div class="card" id = "${item.id}">
<img src="${item.productImage}" alt="Card Image" class="card-image">
<div class="card-content">
<h3 class="card-title" id = "product-name">${item.name} </h3>
<p class="card-price">$${item.price}</p>
<p class="card-description" style = "max-width: 300px; max-height : 60px; overflow: hidden;"> ${item.Description}...</p>
<button class="decrease-quantity" onClick = "decreaseQuantity()">-</button>
<input type="text" class="quantity" value="1" min="1" readOnly>
<button class="increase-quantity" onClick = "increaseQuantity()">+</button>
</div>
<span class="card-icon" id = "delete-card">
<button id = "delete-item" class = "delete">
<i id = "delete-icon"class="fa-solid fa-trash" style = "scale = 1.3;"></i>
</button>
</span>
</div>`;
$('#container').append(productDetail); // add all element one by one by appending to HTML
}
});
});
checkListEmpty();
$('#item-count').text(jsonArray.length);
calculateTotalPrice()
const childrenElements = $(this).children();
// Loop through the children and do something with each child element
childrenElements.each(function (index) {
console.log("Child " + (index + 1) + ": " + $(this).text());
});
$('.card').on('click', function (event) { // make a card clickable
const clickedElementId = $(event.target).attr("id"); // get the id of clicked item
console.log(clickedElementId);
if (clickedElementId == 'delete-item' || clickedElementId == 'delete-card' || clickedElementId == 'delete-icon') { // suggest a better approach for inner clickable button
item = event.target.closest('.card'); // if trash icon is clicked open a alert dialog
deleteItem(event);
}else {
const product = event.target.closest(".card"); // if a card is clicked get its id
var url = 'productDetails.html?id=' + product.id; // send id attribute of the product to prdct details page
window.location.href = url;
}
});
$('delete-item').on('click', function (event) { // trash icon is clicked
event.stopPropagation();
const clickedElement = event.target;
console.log(clickedElement);
item = clickedElement.closest('.card'); // suggest better suggestion
if (item) {
showAlert();
}
})
console.log(jsonData);
//prepareUI(jsonData); // render the data in the ui and make it meaningful
} catch (error) {
console.error('Error fetching data:', error.message); // an error occured while fetching the data
}
}
function prepareUI(jsonData){
console.log("inside prepare UI")
}
/* fetch('./data/products.json')
.then(response => response.json())
.then(data => {
const jsonArray = JSON.parse(localStorage.getItem('IDs'));
jsonArray.forEach(element => {
for (let key in data) {
if (data[key].id == element) {
let element = `<div class="card" id = "${data[key].id}">
<img src="${data[key].productImage}" alt="Card Image" class="card-image">
<div class="card-content">
<h3 class="card-title" id = "product-name">${data[key].name} </h3>
<p class="card-price">$${data[key].price}</p>
<p class="card-description" style = "max-width: 300px; max-height : 60px; overflow: hidden;"> ${data[key].Description}...</p>
<button class="decrease-quantity" onClick = "decreaseQuantity()">-</button>
<input type="text" class="quantity" value="1" min="1" readOnly>
<button class="increase-quantity" onClick = "increaseQuantity()">+</button>
</div>
<span class="card-icon" id = "delete-card">
<button id = "delete-item" class = "delete">
<i id = "delete-icon"class="fa-solid fa-trash" style = "scale = 1.3;"></i>
</button>
</span>
</div>`
container.innerHTML += element;
}
}
});
checkListEmpty();
$('#item-count').text(jsonArray.length);
calculateTotalPrice()
const childrenElements = $(this).children();
// Loop through the children and do something with each child element
childrenElements.each(function (index) {
console.log("Child " + (index + 1) + ": " + $(this).text());
});
$('.card').on('click', function (event) {
const clickedElementId = $(event.target).attr("id"); //$(event.target).hasClass('')
console.log(clickedElementId);
if (clickedElementId == 'delete-item' || clickedElementId == 'delete-card' || clickedElementId == 'delete-icon') { // suggest a better approach for inner clickable button
console.log('Button inside card clicked');
item = event.target.closest('.card'); // suggest better suggestion
deleteItem(event)
}else {
//const productId = this.id; should be passed parametre to the link
const children = this.children;
const product = event.target.closest(".card");
const firstElement = children[1]; // suggest a better approach to find h3 element
const secondElement = firstElement.children;
const targetElement = secondElement[0];
let productName = targetElement.textContent;
var url = 'productDetails.html?id=' + product.id;
window.location.href = url;
}
});
$('delete-item').on('click', function (event) {
event.stopPropagation();
const clickedElement = event.target;
console.log(clickedElement);
item = clickedElement.closest('.card'); // suggest better suggestion
if (item) {
showAlert();
}
})
}); */
function deleteItem(event) {
const clickedElement = event.target;
console.log(clickedElement);
item = clickedElement.closest('.card'); // suggest better suggestion
if (item) {
showAlert();
}
/* const clickedElement = event.target;
const cardElement = clickedElement.closest('.card'); // suggest better suggestion
if (cardElement) {
var idOfProduct = cardElement.id;
removeID(idOfProduct);
cardElement.remove();<
checkListEmpty();
} */
}
function removeItem() {
if (item) {
updateSummary(item); // update checkout details
var idOfProduct = item.id;
removeID(idOfProduct); // remove product id from cart list
hideAlert(); // hide alert dialog the user pressed cancel or delete
item.remove(); // that basic code snippet removes the element from HTML
checkListEmpty(); // check list is empty, if it's empty show a message
}
}
function showAlert() {
const modalOverlay = document.getElementById('modalOverlay');
modalOverlay.style.display = 'block';
}
function hideAlert() {
const modalOverlay = document.getElementById('modalOverlay');
modalOverlay.style.display = 'none';
}
function handleCloseAlertButtonClick() {
hideAlert();
}
function handleDeleteAlertButtonClick() {
removeItem();
}
const closeAlertButton = document.getElementById('closeAlertButton');
closeAlertButton.addEventListener('click', handleCloseAlertButtonClick);
const deleteAlertButton = document.getElementById('deleteAlertButton');
deleteAlertButton.addEventListener('click', handleDeleteAlertButtonClick);
function removeID(id) {
const storedIDs = JSON.parse(localStorage.getItem('IDs'));
const index = storedIDs.indexOf(id);
const newArray = storedIDs.filter((element) => element !== id);
storedIDs.forEach(element => {
if (element == id) {
const newArray = storedIDs.filter((element) => element !== id);
storedIDs.splice(storedIDs.indexOf(element), 1);
saveIDsToLocalStorage(storedIDs);
}
});
if (index !== -1) {
storedIDs.splice(index, 1);
saveIDsToLocalStorage(storedIDs);
}
}
function saveIDsToLocalStorage(IDs) {
const IDsString = JSON.stringify(IDs);
localStorage.setItem('IDs', IDsString);
}
const listContainer = document.getElementById('container');
const emptyListMessage = document.getElementById('empty-list-message');
function checkListEmpty() { // checks if the cart list is empty
if (listContainer.childElementCount === 0) {
emptyListMessage.style.display = 'block'; // show empty list message
//$('.order-summary').hide() // hide checkout section
$('.main-container').hide();
} else {
emptyListMessage.style.display = 'none';
// $('.main-container').hide();
$('.order-summary').show()
}
}
$('#purchase-button').on('click' ,
function (){
window.location.href = "./orderPlaced.html";
});
function openHome() {
window.location.href = "./home.html";
}
function calculateTotalPrice() {
const input = $('.card-price').text();
let total = 0;
const numbersArray = input.match(/\d+(\.\d+)?/g);
console.log(numbersArray);
numbersArray.forEach(each => {
let number = parseInt(each);
total += number;
})
$('#total-price').text(total);
console.log("the total is " + total)
const textContents = [];
$('.card-price').each(function () {
const textContent = $(this).text();
const numbersArray = textContent.match(/\d+(\.\d+)?/g);
textContents.push(numbersArray);
});
console.log(textContents);
/* const numericValues = $('.card-price').text().map((str) => {
const num = str.match(/\d+/);
return parseInt(num);
}); */
textContents.forEach(eachElement => {
console.log(eachElement);
}
)
}
function updateSummary(item) {
let priceString = item.querySelector('.card-price');
const price = priceString.textContent.match(/\d+(\.\d+)?/g);
console.log("the price is "+ price[0]);
let previousPrice = $('#total-price').text()
$('#total-price').text(previousPrice - price[0])
let itemCount = $('#item-count').text();
console.log("last item count is "+itemCount)
let totalItem = parseInt(itemCount);
$('#item-count').text(totalItem - 1);
/* const list = JSON.parse(localStorage.getItem('IDs'))
$('#item-count').text(list.length);
console.log(typeof (item));
console.log($('item-count').text())
itemPrice = parseInt(item.textContent + "the item's text content");
console.log(item);
// const child = item.find(".card-price");
//const grandparentElement = $(".card-content");
const parentElement = item.find(".card-content");
const targetElement = parentElement.find(".card-price");
console.log(targetElement);
//console.log(child.textContent);
$('#total-price').text(parseInt(item.textContent) - itemPrice);
console.log("the total count is " + $('#total-price').text()); */
}
/*
function decreaseQuantity(event) {
const cartItem = event.target.parentNode;
const quantityInput = cartItem.querySelector(".quantity");
let currentQuantity = parseInt(quantityInput.value);
if (currentQuantity > 1) {
currentQuantity--;
quantityInput.value = currentQuantity;
}
} */
$('.increase-quantity').on('click', function () {
console.log("hello world");
});
$('.decrease-quantity').on('click', function () {
console.log("hello world1");
});
function increaseQuantity() {
/* const cartItem = event.target.parentNode;
const quantityInput = cartItem.querySelector(".quantity");
let currentQuantity = parseInt(quantityInput.value);
currentQuantity++;
quantityInput.value = currentQuantity; */
let currentQuantity = $('.quantity').text();
console.log(currentQuantity);
console.log($('.quantity').text());
//$('.quantity').text(currentQuantity);
}
function decreaseQuantity() {
/*const cartItem = event.target.parentNode;
const quantityInput = cartItem.querySelector(".quantity");
let currentQuantity = parseInt(quantityInput.value);
currentQuantity++;
quantityInput.value = currentQuantity;*/
let currentQuantity = $('.quantity').text();
console.log(currentQuantity);
console.log($('.quantity').text());
}
const person = {
name: 'John Doe', // can be accessed as person.name
age: 30,
isEmployed: true
};
const fruits = ['apple', 'banana', 'orange'];
fruits.push('grape'); // add element
fruits.pop(); // remove last element
fruits.length; // lenght of the array
fruits.indexOf('banana'); // gives index of the element