-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
183 lines (162 loc) · 6.48 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
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
// variables and constants
const cartContainer = document.querySelector('.cart-container');
const productList = document.querySelector('.product-list');
const cartList = document.querySelector('.cart-list');
const cartTotalValue = document.getElementById('cart-total-value');
const cartCountInfo = document.getElementById('cart-count-info');
let cartItemID = 1;
eventListeners();
// all event listeners
function eventListeners(){
window.addEventListener('DOMContentLoaded', () => {
loadJSON();
loadCart();
});
// toggle navbar when toggle button is clicked
document.querySelector('.navbar-toggler').addEventListener('click', () => {
document.querySelector('.navbar-collapse').classList.toggle('show-navbar');
});
// show/hide cart container
document.getElementById('cart-btn').addEventListener('click', () => {
cartContainer.classList.toggle('show-cart-container');
});
// add to cart
productList.addEventListener('click', purchaseProduct);
// delete from cart
cartList.addEventListener('click', deleteProduct);
}
// update cart info
function updateCartInfo(){
let cartInfo = findCartInfo();
cartCountInfo.textContent = cartInfo.productCount;
cartTotalValue.textContent = cartInfo.total;
}
// load product items content form JSON file
function loadJSON(){
fetch('shirts.json')
.then(response => response.json())
.then(data =>{
let html = '';
data.forEach(product => {
html += `
<div class = "product-item">
<div class = "product-img">
<img src = "${product.imgSrc}" alt = "product image">
<button type = "button" class = "add-to-cart-btn">
<i class = "fas fa-shopping-cart"></i>Add To Basket
</button>
</div>
<div class = "product-content">
<h3 class = "product-name">${product.name}</h3>
<span class = "product-category">${product.category}</span> <br />
<span class = "product-size">${product.size}</span> <br />
<span class = "product-color">${product.color}</span>
<p class = "product-price">£${product.price}</p>
</div>
</div>
`;
});
productList.innerHTML = html;
})
.catch(error => {
alert(`User live server or local server`);
//URL scheme must be "http" or "https" for CORS request. You need to be serving your index.html locally or have your site hosted on a live server somewhere for the Fetch API to work properly.
})
}
// purchase product
function purchaseProduct(e){
if(e.target.classList.contains('add-to-cart-btn')){
let product = e.target.parentElement.parentElement;
getProductInfo(product);
}
}
// get product info after add to cart button click
function getProductInfo(product){
let productInfo = {
id: cartItemID,
imgSrc: product.querySelector('.product-img img').src,
name: product.querySelector('.product-name').textContent,
category: product.querySelector('.product-category').textContent,
size: product.querySelector('.product-size').textContent,
color: product.querySelector('.product-color').textContent,
price: product.querySelector('.product-price').textContent
}
cartItemID++;
addToCartList(productInfo);
saveProductInStorage(productInfo);
}
// add the selected product to the cart list
function addToCartList(product){
const cartItem = document.createElement('div');
cartItem.classList.add('cart-item');
cartItem.setAttribute('data-id', `${product.id}`);
cartItem.innerHTML = `
<img src = "${product.imgSrc}" alt = "product image">
<div class = "cart-item-info">
<h3 class = "cart-item-name">${product.name}</h3>
<span class = "cart-item-category">${product.category}</span>
<span class = "cart-item-size">${product.size}</span>
<span class = "cart-item-color">${product.color}</span>
<span class = "cart-item-price">${product.price}</span>
</div>
<button type = "button" class = "cart-item-del-btn">
<i class = "fas fa-times"></i>
</button>
`;
cartList.appendChild(cartItem);
}
// save the product in the local storage
function saveProductInStorage(item){
let products = getProductFromStorage();
products.push(item);
localStorage.setItem('products', JSON.stringify(products));
updateCartInfo();
}
// get all the products info if there is any in the local storage
function getProductFromStorage(){
return localStorage.getItem('products') ? JSON.parse(localStorage.getItem('products')) : [];
// returns empty array if there isn't any product info
}
// load carts product
function loadCart(){
let products = getProductFromStorage();
if(products.length < 1){
cartItemID = 1; // if there is no any product in the local storage
} else {
cartItemID = products[products.length - 1].id;
cartItemID++;
// else get the id of the last product and increase it by 1
}
products.forEach(product => addToCartList(product));
// calculate and update UI of cart info
updateCartInfo();
}
// calculate total price of the cart and other info
function findCartInfo(){
let products = getProductFromStorage();
let total = products.reduce((acc, product) => {
let price = parseFloat(product.price.substr(1)); // removing dollar sign
return acc += price;
}, 0); // adding all the prices
return{
total: total.toFixed(2),
productCount: products.length
}
}
// delete product from cart list and local storage
function deleteProduct(e){
let cartItem;
if(e.target.tagName === "BUTTON"){
cartItem = e.target.parentElement;
cartItem.remove(); // this removes from the DOM only
} else if(e.target.tagName === "I"){
cartItem = e.target.parentElement.parentElement;
cartItem.remove(); // this removes from the DOM only
}
let products = getProductFromStorage();
let updatedProducts = products.filter(product => {
return product.id !== parseInt(cartItem.dataset.id);
});
localStorage.setItem('products', JSON.stringify(updatedProducts)); // updating the product list after the deletion
updateCartInfo();
}