-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
287 lines (262 loc) · 8.78 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
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
const itemsSection = document.getElementsByClassName('items')[0];
const carrinho = document.getElementsByClassName('cart__items')[0];
const lista = document.querySelector('.cart__items');
const savedItems = getSavedCartItems();
const btnClear = document.getElementsByClassName('empty-cart')[0];
const subtotalDiv = document.querySelector('.subtotal');
const searchImput = document.getElementById('search');
const btnSearch = document.getElementById('btn-search');
const moveTop = document.getElementById('move-up');
const cartIcon = document.getElementsByClassName('material-icons')[0];
const cartContainer = document.querySelector('.cart');
const cartTitle = document.querySelector('.container-cartTitle');
const hideMenu = () => {
cartIcon.addEventListener('click', () => {
const classModify = 'close-cart-items';
cartContainer.classList.toggle(classModify);
cartTitle.classList.toggle(classModify);
if (cartTitle.classList.contains(classModify)) {
setTimeout(() => {
cartContainer.style.display = 'none';
cartTitle.style.display = 'none';
}, 200);
} else {
setTimeout(() => {
cartContainer.style.display = 'flex';
cartTitle.style.display = 'flex';
}, 200);
}
});
};
hideMenu();
const moveUp = () => {
moveTop.addEventListener(('click'), () => {
itemsSection.scrollIntoView({ behavior: 'smooth' });
});
};
const getCartItemsPrices = () => {
let arrayPrices = [];
const savedCartItems = JSON.parse(localStorage.getItem('cartItems'));
if (savedCartItems !== null) {
if (savedCartItems.length > 0) {
arrayPrices = savedCartItems.map((element) => (element.price));
}
} else {
arrayPrices = [];
}
return (arrayPrices);
};
// https://stackoverflow.com/questions/3163070/javascript-displaying-a-float-to-2-decimal-places
function round(value, decimals) {
return Number(`${Math.round(`${value}e${decimals}`)}e-${decimals}`);
}
const getTotalPrice = () => {
const arrayPrices = getCartItemsPrices();
let totalPrice = 0;
for (let index = 0; index < arrayPrices.length; index += 1) {
totalPrice += arrayPrices[index];
totalPrice = round(totalPrice, 2);
}
return (totalPrice);
};
const totalPrice = () => {
const price = getTotalPrice();
if (document.querySelector('.total-price')) {
document.querySelector('.total-price').remove();
}
const paragraph = document.createElement('p');
paragraph.classList = 'total-price';
paragraph.innerText = `TOTAL: ${price}`;
subtotalDiv.appendChild(paragraph);
};
// Essa função adiciona os itens no localstorage
const getClickedItem = (objeto) => {
const savedInCart = JSON.parse(localStorage.getItem('cartItems'));
let arrayLi = savedInCart !== null ? savedInCart : [];
for (let index = 0; index < carrinho.childNodes.length; index += 1) {
if (index > 0) {
arrayLi = [...savedInCart, objeto];
} else {
arrayLi = [objeto];
}
}
saveCartItems(JSON.stringify(arrayLi));
};
const cartItemClickListener = async (event, objeto) => {
const listaCart = document.querySelector('ol');
const savedCartItems = JSON.parse(localStorage.getItem('cartItems'));
let indexToRemove = 0;
savedCartItems.forEach((element, index) => {
indexToRemove = element.id === objeto.id ? index : 0;
});
const itemToRemove = event.target.parentNode;
itemToRemove.id = 'remover';
// https://developer.mozilla.org/pt-BR/docs/Web/API/Node/removeChild
const elemento = document.getElementById('remover');
const divToRemove = elemento.parentNode;
divToRemove.parentNode.removeChild(divToRemove);
localStorage.setItem('cartItems', JSON.stringify(savedCartItems
.filter((element, index) => (index !== indexToRemove))));
totalPrice();
return listaCart;
};
const liContainer = (objeto) => {
const liCont = document.createElement('div');
liCont.className = 'cartItem-div';
liCont.id = `li-${objeto.id}`;
return liCont;
};
const liContainerSaved = ({ id, img }) => {
const liCont = document.createElement('div');
const image = document.createElement('img');
image.src = img;
liCont.className = 'cartItem-div';
liCont.id = `li-${id}`;
liCont.appendChild(image);
return liCont;
};
const liTextSaved = (objeto) => {
const { title, id, price } = objeto;
const liTitle = document.createElement('p');
liTitle.innerText = title;
const liId = document.createElement('span');
liId.innerText = `ID: ${id}`;
const liPrice = document.createElement('span');
liPrice.innerText = `PREÇO: ${price}`;
const li = document.createElement('li');
li.className = 'cart__item';
li.appendChild(liTitle);
li.appendChild(liId);
li.appendChild(liPrice);
li.addEventListener('click', function (event) {
cartItemClickListener(event, objeto);
});
return li;
};
const carregaLista = () => {
if (localStorage.getItem('cartItems') !== null) {
const arrayItems = JSON.parse(savedItems);
for (let index = 0; index < arrayItems.length; index += 1) {
const item = arrayItems[index];
const divContainer = liContainerSaved(item);
lista.appendChild(divContainer);
divContainer.appendChild(liTextSaved(arrayItems[index]));
}
}
};
const creatCartItemImg = (objeto) => {
const imageContainer = document.createElement('img');
imageContainer.src = objeto.thumbnail;
imageContainer.className = 'img-cartItem';
return imageContainer;
};
const createCartItemElement = (objeto) => {
const { id, title, price } = objeto;
const liTitle = document.createElement('p');
liTitle.innerText = title;
const liId = document.createElement('span');
liId.innerText = `ID: ${id}`;
const liPrice = document.createElement('span');
liPrice.innerText = `PREÇO: ${price}`;
const li = document.createElement('li');
li.className = 'cart__item';
li.appendChild(liTitle);
li.appendChild(liId);
li.appendChild(liPrice);
li.addEventListener('click', function (event) {
cartItemClickListener(event, objeto);
});
return li;
};
const createProductImageElement = (imageSource) => {
const img = document.createElement('img');
img.className = 'item__image';
img.src = imageSource;
return img;
};
const createCustomElement = (element, className, innerText) => {
const e = document.createElement(element);
e.className = className;
e.innerText = innerText;
return e;
};
const createProductItemElement = ({ id, title, thumbnail, price }) => {
const section = document.createElement('section');
section.className = 'item';
section.appendChild(createCustomElement('span', 'item_id', id));
section.appendChild(createProductImageElement(thumbnail));
section.appendChild(createCustomElement('span', 'item__title', title));
section.appendChild(createCustomElement('span', 'item__price', `PREÇO ${price}`));
section.appendChild(createCustomElement('button', 'item__add', 'Adicionar ao carrinho!'));
return section;
};
const creatObjectItem = (objeto) => {
const item = {
id: objeto.id,
img: objeto.thumbnail,
price: objeto.price,
title: objeto.title,
};
return item;
};
const objetoAdicionar = async () => {
const arrayItemAdd = document.querySelectorAll('.item__add');
arrayItemAdd.forEach(async (btn) => {
btn.addEventListener('click', async (event) => {
const idTarget = event.target.parentElement.firstChild.innerText;
const objeto = await fetchItem(idTarget);
const newObj = creatObjectItem(objeto);
const divitem = carrinho.appendChild(liContainer(newObj));
divitem.appendChild(creatCartItemImg(objeto));
divitem.appendChild(createCartItemElement(newObj));
getClickedItem(newObj);
totalPrice();
});
});
};
const loadingFunction = () => {
const loadParagraph = document.createElement('p');
loadParagraph.classList = 'loading';
loadParagraph.innerText = 'carregando...';
itemsSection.appendChild(loadParagraph);
};
const clearProducts = () => {
while (itemsSection.childNodes.length > 0) {
itemsSection.removeChild(itemsSection.firstChild);
}
};
const criarLista = async (end) => {
clearProducts();
loadingFunction();
const objeto = await fetchProducts(end);
const arrayItems = objeto.results;
arrayItems.forEach((item) => {
itemsSection.appendChild(createProductItemElement(item));
});
await objetoAdicionar();
totalPrice();
document.querySelector('.loading').remove();
};
const searchProduct = () => {
btnSearch.addEventListener('click', () => {
const valorBuscado = (searchImput.value).toLowerCase();
criarLista(valorBuscado);
});
};
const clearFunction = () => {
btnClear.addEventListener('click', () => {
while (carrinho.childNodes.length > 0) {
carrinho.removeChild(carrinho.firstChild);
}
localStorage.setItem('cartItems', '[]');
totalPrice();
});
};
window.onload = () => {
criarLista();
carregaLista();
clearFunction();
searchProduct();
moveUp();
totalPrice();
};