Simple Shopping Cart with pure Javascript

Hamid Haghdoost - May 18 '22 - - Dev Community

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

and finally we update the cart based on the current cart items:

function updateCart() {
    document.getElementById("sum").textContent = sum;
    document.getElementById("count").textContent = count;
}
Enter fullscreen mode Exit fullscreen mode

Complete code is available in this github repo. If you find it useful give it a star please :)

. . . . . . . . . . .