-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.js
87 lines (76 loc) · 2.12 KB
/
main2.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
//query selectors
let prod = document.getElementById('prod-item');
let basket = JSON.parse(localStorage.getItem("data")) || [];
//generate crart items
let generate = () => {
return (prod.innerHTML= storeData
.map((x) => {
let {id, name, price, img} = x;
let search = basket.find((x) => x.id === id ) || [];
return `
<div class="item1" id=product-id-${id}>
<div>
<img id="myImg" src=${img} alt="Agbada" />
</div>
<div class="form-item" id="item-content">
<div class="item-txt">
<h2>${name}</h2>
</div>
<form>
<div class="input">
<input class="price" type="text" id="price" name="price" value="₦${price},000" readonly>
</div>
<div class="quant">
<button class="quantity-minus" type="button" onclick="decrement(${id})">-</button>
<h5 id=${id} class="quantity">${search.item === undefined ? 0: search.item}</h5>
<button class="quantity-plus" type="button" onclick="increment(${id})">+</button>
</div>
</form>
</div>
</div>
`;
})
.join(""));
};
generate();
//increment
let increment = (id) =>{
let selectedItem = id;
let search = basket.find((x) => x.id === selectedItem.id)
if (search === undefined){
basket.push({
id: selectedItem.id,
item: 1,
});
}else{
search.item += 1;
}
//console.log(basket);
update(selectedItem.id);
localStorage.setItem("data", JSON.stringify(basket));
};
//dcerement
let decrement = (id) =>{
let selectedItem = id;
let search = basket.find((x) => x.id === selectedItem.id);
if(search === undefined) return;
else if (search.x === 0 )return;
else{
search.item -= 1;
}
update(selectedItem.id);
basket = basket.filter((x) => x.item !== 0);
localStorage.setItem("data", JSON.stringify(basket));
};
//update in real time
let update = (id) =>{
let search = basket.find((x) => x.id === id);
document.getElementById(id).innerHTML = search.item;
calculation();
};
//calculate
let calculation =() => {
let cartIcon = document.getElementById("count");
cartIcon.innerHTML = basket.map((x) => x.item).reduce((x,y) => x+y,0);
}
calculation();