-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart.js
102 lines (83 loc) · 2.63 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
window.onload = function () {
cartCounter()
btAddCart()
addToHtml()
function getS() {
var productList = [];
if (localStorage.getItem('myCart') !== null) {
productList = JSON.parse(localStorage.getItem('myCart'));
} else {
productList = [];
}
return productList;
}
function cartCounter() {
var cartCount = document.querySelector('.js-cart-count');
if (cartCount) {
cartCount.innerHTML = getS().length;
}
}
function btAddCart() {
var buttonAddCart = document.querySelector('.js-add-cart');
if (buttonAddCart) {
buttonAddCart.addEventListener('click', function () {
var itemId = document.querySelector('.js-item-id').innerHTML;
var itemName = document.querySelector('.js-item-name').innerHTML;
var item = getS().find(function (i) {
return i.id === itemId;
});
if (item === undefined) {
var newProduct = {
id: itemId,
name: itemName
};
var prList = getS()
prList.push(newProduct);
var myCart = JSON.stringify(prList);
localStorage.setItem('myCart', myCart);
addToHtml()
cartCounter()
}
});
}
}
function addToHtml() {
var productFromCart = document.querySelector('#productFromCart');
productFromCart.innerHTML = '';
var productInCart = getS();
var fragment = document.createDocumentFragment();
for (var i = 0; i < productInCart.length; i++) {
var line = document.createElement('div');
line.classList.add("user-cart-list-line");
line.innerHTML = "<div><span class=\"user-cart-list-line-num\">".concat(i + 1, ".</span> ").concat(productInCart[i].name, "</div>");
var del = document.createElement('span');
del.classList.add("user-cart-list-line-delete")
del.dataset.id = productInCart[i].id;
line.appendChild(del);
fragment.appendChild(line);
del.addEventListener('click', function () {
var dataId = this.getAttribute('data-id');
var index = productInCart.findIndex(
function (i) {
return i.id == dataId;
}
);
productInCart.splice(index, 1);
var myCarts = JSON.stringify(productInCart);
localStorage.setItem('myCart', myCarts);
cartCounter()
addToHtml()
})
}
productFromCart.appendChild(fragment);
var form = document.querySelector('[name="products"]');
if (form) {
form.value = JSON.stringify(productInCart);
}
}
function clearCart() {
localStorage.removeItem('myCart');
cartCounter();
addToHtml()
}
}