I'm a code mentor and private programming tutor. Today, me and my student was working on event listeners on JS and I tried to teach how to make a simple and minimal shopping cart. If you are learning JS, this could be a good exercise. You can find code here.
In this work we added our products like this:
<div class="product">
<h3>Product one</h3>
<p>Price: 2000</p>
<button data-id="1" data-price="2000">Add to cart</button>
</div>
We know that in real world we do not this manually and we generate them with loops and we put data that we have got from database maybe.
also we have a nav-bar like this:
<div class="toolbar">
<h1 class="brand">Shop</h1>
<p>
Cart items:
<span id="count">0</span>,
Price:
<span id="sum">0</span>
</p>
</div>
And in JS file we try to add event listener on add btns:
let btns = document.querySelectorAll(".products button");
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", add);
}
and then we try to add or remove the items based on the state of product in the cart:
function add(event) {
let price = Number(event.target.dataset.price);
let index = cart.indexOf(event.target.dataset.id);
console.log(cart, index);
if (index >= 0) {
cart.splice(index, 1)
count--;
sum -= price;
event.target.className = "";
event.target.textContent = "Add to cart";
} else {
cart.push(event.target.dataset.id);
count++;
sum += price;
event.target.className = "added";
event.target.textContent = "Remove";
}
updateCart();
}
and finally we update the cart based on the current cart items:
function updateCart() {
document.getElementById("sum").textContent = sum;
document.getElementById("count").textContent = count;
}
Complete code is available in this github repo. If you find it useful give it a star please :)
Top comments (0)