-
Notifications
You must be signed in to change notification settings - Fork 6
/
incrementDecrement.js
56 lines (41 loc) · 1.52 KB
/
incrementDecrement.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
import { getCartProductFromLS } from "./getCartProducts";
import { updateCartProductTotal } from "./updateCartProductTotal";
export const incrementDecrement = (event, id, stock, price) => {
const currentCardElement = document.querySelector(`#card${id}`);
const productQuantity = currentCardElement.querySelector(".productQuantity");
const productPrice = currentCardElement.querySelector(".productPrice");
let quantity = 1;
let localStoragePrice = 0;
let localCartProducts = getCartProductFromLS();
let existingProd = localCartProducts.find((curProd) => curProd.id === id);
if (existingProd) {
quantity = existingProd.quantity;
localStoragePrice = existingProd.price;
} else {
localStoragePrice = price;
price = price;
}
if (event.target.className === "cartIncrement") {
if (quantity < stock) {
quantity += 1;
} else if (quantity === stock) {
quantity = stock;
localStoragePrice = price * stock;
}
}
if (event.target.className === "cartDecrement") {
if (quantity > 1) {
quantity -= 1;
}
}
localStoragePrice = price * quantity;
localStoragePrice = Number(localStoragePrice.toFixed(2));
let updatedCart = { id, quantity, price: localStoragePrice };
updatedCart = localCartProducts.map((curProd) => {
return curProd.id === id ? updatedCart : curProd;
});
localStorage.setItem("cartProductLS", JSON.stringify(updatedCart));
productQuantity.innerText = quantity;
productPrice.innerText = localStoragePrice;
updateCartProductTotal();
};