const product = [
{
id: 0,
image:
title:
"MERN stack course"
,
price: 21999,
},
{
id: 1,
image:
title:
"DSA self placed"
,
price: 21999,
},
{
id: 2,
image:
title:
"Gate 2024"
,
price: 6999,
},
{
id: 3,
image:
title:
"DevOps course"
,
price: 11999,
},
];
const categories = [...
new
Set(product.map((item) => {
return
item;}))];
let i = 0;
document.getElementById(
"root"
).innerHTML = categories
.map((item) => {
var
{ image, title, price } = item;
return
(
`<div class=
'box'
>
<div class=
'img-box'
>
<img class=
'images'
src=${image}></img>
</div>
<div class=
'bottom'
>
<p>${title}</p>
<h2>₹ ${price}</h2>` +
"<button onclick='addtocart("
+i++ +
")'>Add to cart</button>"
+`</div> </div>`
);
}).join(
""
);
var
cart = [];
function
addtocart(a) {
const selectedProduct = { ...categories[a] };
const existingItem = cart.find(item => item.id === selectedProduct.id);
if
(existingItem) {
existingItem.quantity = (existingItem.quantity || 1) + 1;
}
else
{
selectedProduct.quantity = 1;
cart.push(selectedProduct);
}
displaycart();
}
function
delElement(a) {
cart.splice(a, 1);
displaycart();
}
let checkoutTotal = 0;
let total = 0;
function
displaycart() {
let j = 0;
total = 0;
if
(cart.length == 0) {
document.getElementById(
"cartItem"
).innerHTML =
"Your cart is empty"
;
document.getElementById(
"total"
).innerHTML =
"₹ "
+ 0;
document.getElementById(
"checkoutCard"
).style.display =
"none"
;
}
else
{
let totalquan = 0;
document.getElementById(
"cartItem"
).innerHTML = cart
.map((items, idx) => {
var
{ image, title, price, quantity } = items;
totalquan += quantity;
document.getElementById(
"count"
).innerHTML = totalquan;
total = total + price * quantity;
document.getElementById(
"total"
).innerHTML =
"₹ "
+ total +
""
;
return
(
`<div class=
'cart-item'
>
<div class=
'row-img'
>
<img class=
'rowimg'
src=${image}>
</div>
<p style=
'font-size:12px;'
>${title}</p>
<h2 style=
'font-size: 15px;'
>₹ ${price}</h2>
<h3>${quantity}</h3>` +
"<i class='fa-solid fa-trash' onclick='delElement("
+j++ +
")'></i></div>"
);
}).join(
""
);
document.getElementById(
"checkout"
).innerHTML =
`<button onclick=
"openCheckout()"
>Checkout</button>`;}}
function
openCheckout() {
document.getElementById(
"checkoutCard"
).style.display =
"block"
;
document.getElementById(
"checkoutTotal"
).innerHTML =
"₹ "
+ total;
}
function
closeCheckout() {
document.getElementById(
"checkoutCard"
).style.display =
"none"
;
}