-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
100 lines (87 loc) · 2.9 KB
/
script.js
File metadata and controls
100 lines (87 loc) · 2.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
let basketBtns = document.querySelectorAll('.toBasketBtn');
basketBtns.forEach(function(btn){
btn.addEventListener('click',function(event){
let id = event.srcElement.dataset.id;
let price = event.srcElement.dataset.price;
let name = event.srcElement.dataset.name;
basket.addProduct({id: id, price: price, name: name})
})
});
let basket = {
products: {},
addProduct(product){
this.addProductToObject(product);
this.renderProductInBasket(product);
this.renderTotalSum();
this.addRemoveBtnsListeners();
},
removeProductListener(event){
basket.removeProduct(event);
basket.renderTotalSum();
},
removeProduct(event){
let id = event.srcElement.dataset.id;
this.removeProductFromObject(id);
this.removeProductFromBasket(id);
},
removeProductFromBasket(id){
let countId = document.querySelector(`.productCount[data-id="${id}"]`);
if(countId.textContent == 1){
countId.parentNode.remove();
} else{
countId.textContent--;
}
},
removeProductFromObject(id){
if(this.products[id].count == 1){
delete this.products[id]
} else {
this.products[id].count--;
}
},
addRemoveBtnsListeners(){
let btns = document.querySelectorAll('.productRemoveBtn');
for(let i = 0; i < btns.length; i++){
btns[i].addEventListener('click',this.removeProductListener);
}
},
renderTotalSum(){
document.querySelector('.total').textContent = this.getTotalSum();
},
getTotalSum(){
let sum = 0;
for(let key in this.products){
sum += this.products[key].price * this.products[key].count;
}
return sum;
},
addProductToObject(product){
if(this.products[product.id] == undefined){
this.products[product.id] = {
price: product.price,
name: product.name,
count: 1
}
} else{
this.products[product.id].count++;
}
},
renderProductInBasket(product){
let productExist = document.querySelector(`.productCount[data-id="${product.id}"]`);
if(productExist){
productExist.textContent++;
return;
}
let productRow = `
<tr>
<th scope="row">${product.id}</th>
<td>${product.name}</td>
<td>${product.price}</td>
<td class="productCount" data-id="${product.id}">1</td>
<td><i class="fas fa-trash-alt productRemoveBtn" data-id="${product.id}"></i></td>
</tr>
`;
let tbody = document.querySelector('tbody');
tbody.insertAdjacentHTML("beforeend", productRow);
}
}