-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
112 lines (110 loc) · 2.89 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
let openShopping = document.querySelector(".shopping");
let closeShopping = document.querySelector(".closeShopping");
let list = document.querySelector(".list");
let listCard = document.querySelector(".listCard");
let body = document.querySelector("body");
let total = document.querySelector(".total");
let quantity = document.querySelector(".quantity");
openShopping.addEventListener("click", () => {
body.classList.add("active");
});
closeShopping.addEventListener("click", () => {
body.classList.remove("active");
});
let products = [
{
id: 1,
name: "Hunter Bridle w/ Reins",
image: "1.PNG",
price: 99.99,
},
{
id: 2,
name: "Close Contact Jump Saddle",
image: "2.PNG",
price: 334.99,
},
{
id: 3,
name: "Stable Rug 400g",
image: "3.PNG",
price: 169.99,
},
{
id: 4,
name: "Rambo Travel Boots",
image: "4.PNG",
price: 86.99,
},
{
id: 5,
name: "Bee Combo Fly Rug",
image: "5.PNG",
price: 59.99,
},
{
id: 6,
name: "Treeless ANTI SLIP saddle pad",
image: "6.PNG",
price: 49.99,
},
];
let listCards = [];
function initApp() {
products.forEach((value, key) => {
let newDiv = document.createElement("div");
newDiv.classList.add("item");
newDiv.innerHTML = `
<img src="image/${value.image}">
<div class="title">${value.name}</div>
<div class="price">£${value.price.toLocaleString()}</div>
<button onclick="addToCard(${key})">Add To Card</button>`;
list.appendChild(newDiv);
});
}
initApp();
function addToCard(key) {
if (listCards[key] == null) {
// copy product form list to list card
listCards[key] = JSON.parse(JSON.stringify(products[key]));
listCards[key].quantity = 1;
}
reloadCard();
}
function reloadCard() {
listCard.innerHTML = "";
let count = 0;
let totalPrice = 0;
listCards.forEach((value, key) => {
totalPrice = totalPrice + value.price;
count = count + value.quantity;
if (value != null) {
let newDiv = document.createElement("li");
newDiv.innerHTML = `
<div><img src="image/${value.image}"/></div>
<div>${value.name}</div>
<div>£${value.price.toLocaleString()}</div>
<div>
<button onclick="changeQuantity(${key}, ${
value.quantity - 1
})">-</button>
<div class="count">${value.quantity}</div>
<button onclick="changeQuantity(${key}, ${
value.quantity + 1
})">+</button>
</div>`;
listCard.appendChild(newDiv);
}
});
total.innerText = `£ ${totalPrice.toLocaleString()}`;
quantity.innerText = count;
}
function changeQuantity(key, quantity) {
if (quantity == 0) {
delete listCards[key];
} else {
listCards[key].quantity = quantity;
listCards[key].price = quantity * products[key].price;
}
reloadCard();
}