-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
260 lines (247 loc) · 8.27 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
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
// If you want to use "products.json" file, you've to comment and uncomment a few lines just in case you do not want to use "contentful API".
// First, comment these below lines from here to...
const client = contentful.createClient({
// This is the space ID. A space is like a project folder in Contentful terms
space : 'YOUR_OWN_Space ID',
// This is the access token for this space. Normally you get both ID and the token in the Contentful web app
accessToken : 'YOUR_OWN_Content Delivery API - access token',
});
// console.log(client);
// ...to here. Then...
// all vars:
const cartBtn = document.querySelector('.cart-btn'); // in navbar
const cartItems = document.querySelector('.cart-items'); // in navbar
const productsDOM = document.querySelector('.products-center');
// cart section - all:
const cartOverlay = document.querySelector('.cart-overlay');
const cartDOM = document.querySelector('.cart');
const cartContent = document.querySelector('.cart-content');
const cartTotal = document.querySelector('.cart-total');
const closeCartBtn = document.querySelector('.close-cart');
const clearCartBtn = document.querySelector('.clear-cart');
// const btnS = document.querySelectorAll('.bag-btn');
// console.log(btnS); // it'll render a Node List.
// Cart items:
let cart = [];
// All Buttons:
let buttonsDOM = [];
// getting the products:
class Products {
async getProducts () {
try {
// ...then comment these lines to use products.json file from here...
let contentful = await client.getEntries({
content_type : 'fashionFurniture',
});
// ... to here.
// uncomment these three lines to use products.json file from here...
// let result = await fetch('products.json');
// let data = await result.json();
// let products = data.items;
// ...to here.
// comment this line to use products.json file from here...
let products = contentful.items;
// ...to here. And this is it. This website is good to go without API.
products = products.map((item) => {
const { title, price } = item.fields;
const { id } = item.sys;
const image = item.fields.image.fields.file.url;
return { title, price, id, image };
});
return products;
} catch (error) {
console.log(error);
}
}
}
// display products:
class UI {
displayProducts (products) {
// console.log(products);
let result = '';
products.forEach((product) => {
result += `
<!-- single product -->
<article class="product">
<div class="img-container">
<img src=${product.image} alt="product" class="product-img">
<button class="bag-btn" data-id=${product.id}>
<i class="fas fa-shopping-cart"></i> add to cart
</button>
</div>
<h3>${product.title}</h3>
<h4>$${product.price}</h4>
</article>
<!-- single product article ends -->
`;
});
return (productsDOM.innerHTML = result);
// productsDOM.innerHTML = result;
}
getBagButtons () {
const buttons = [ ...document.querySelectorAll('.bag-btn') ]; // So it'll give us an array instead of Node list.
buttonsDOM = buttons;
buttons.forEach((button) => {
let id = button.dataset.id;
let inCart = cart.find((item) => id === item.id);
if (inCart) {
button.innerText = 'In Cart';
button.disabled = true;
}
button.addEventListener('click', (event) => {
event.target.innerText = 'In Cart';
event.target.disabled = true;
// get product from products based on the id we're getting:
let cartItem = { ...Storage.getProduct(id), count: 1 };
// add product to the cart:
cart = [ ...cart, cartItem ];
// save cart in local storage:
Storage.saveCart(cart);
// set cart values:
this.setCartValues(cart);
// add and display cart item:
this.addCartItem(cartItem);
// show the cart:
this.showCart();
});
});
}
setCartValues (cart) {
let startingPriceTotal = 0;
let itemsCountTotal = 0;
cart.map((item) => {
startingPriceTotal += item.count * item.price;
itemsCountTotal += item.count;
});
cartTotal.innerText = parseFloat(startingPriceTotal.toFixed(2));
cartItems.innerText = itemsCountTotal;
// console.log(cartTotal, cartItems);
}
addCartItem (item) {
const div = document.createElement('div');
div.classList.add('cart-item');
div.innerHTML = `
<img src=${item.image} alt="product item">
<div>
<h4>${item.title}</h4>
<h5>$${item.price}</h5>
<span class="remove-item" data-id=${item.id}>remove</span>
</div>
<div>
<i class="fas fa-chevron-up" data-id=${item.id}></i>
<p class="item-amount">${item.count}</p>
<i class="fas fa-chevron-down" data-id=${item.id}></i>
</div>
`;
cartContent.appendChild(div);
// console.log(cartContent);
}
showCart () {
cartOverlay.classList.add('transparentBcg');
cartDOM.classList.add('showCart');
}
setupWholeWeb () {
cart = Storage.getCart();
this.setCartValues(cart);
this.populateCart(cart);
cartBtn.addEventListener('click', this.showCart);
closeCartBtn.addEventListener('click', this.hideCart);
}
populateCart (cart) {
cart.forEach((item) => this.addCartItem(item));
}
hideCart () {
cartOverlay.classList.remove('transparentBcg');
cartDOM.classList.remove('showCart');
}
cartLogic () {
// clear cart button:
clearCartBtn.addEventListener('click', () => this.clearCartMethod());
// cart functionality:
cartContent.addEventListener('click', (event) => {
if (event.target.classList.contains('remove-item')) {
let removeItem = event.target;
let id = removeItem.dataset.id;
cartContent.removeChild(removeItem.parentElement.parentElement);
this.removeItem(id);
} else if (event.target.classList.contains('fa-chevron-up')) {
let addCount = event.target;
let id = addCount.dataset.id;
let temporaryItemInCart = cart.find((item) => item.id === id);
temporaryItemInCart.count = temporaryItemInCart.count + 1;
Storage.saveCart(cart);
this.setCartValues(cart);
addCount.nextElementSibling.innerText = temporaryItemInCart.count;
} else if (event.target.classList.contains('fa-chevron-down')) {
let lowerCount = event.target;
let id = lowerCount.dataset.id;
let temporaryItemInCart = cart.find((item) => item.id === id);
temporaryItemInCart.count = temporaryItemInCart.count - 1;
if (temporaryItemInCart.count > 0) {
Storage.saveCart(cart);
this.setCartValues(cart);
lowerCount.previousElementSibling.innerText = temporaryItemInCart.count;
} else {
cartContent.removeChild(lowerCount.parentElement.parentElement);
this.removeItem(id);
}
}
});
}
clearCartMethod () {
// console.log(this);
let cartItems = cart.map((item) => item.id);
// console.log(cartItems);
cartItems.forEach((id) => this.removeItem(id));
// console.log(cartContent.children);
while (cartContent.children.length > 0) {
cartContent.removeChild(cartContent.children[0]);
}
this.hideCart();
}
removeItem (id) {
cart = cart.filter((item) => id !== item.id);
this.setCartValues(cart);
Storage.saveCart(cart);
let button = this.getSingleBtn(id);
button.disabled = false;
button.innerHTML = `<i class="fas fa-shopping-cart"></i> add to cart`;
}
getSingleBtn (id) {
return buttonsDOM.find((button) => button.dataset.id === id);
}
}
// local storage:
class Storage {
static saveProducts (products) {
localStorage.setItem('products', JSON.stringify(products));
}
static getProduct (id) {
let products = JSON.parse(localStorage.getItem('products'));
return products.find((product) => id === product.id);
}
static saveCart (cart) {
localStorage.setItem('cart', JSON.stringify(cart));
}
static getCart () {
return localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) :
[];
}
}
document.addEventListener('DOMContentLoaded', () => {
const ui = new UI();
const products = new Products();
// setup Whole Web:
ui.setupWholeWeb();
ui.cartLogic();
// get ALL products
products
.getProducts()
.then((products) => {
ui.displayProducts(products);
Storage.saveProducts(products);
})
.then(() => {
ui.getBagButtons();
});
});