DEV Community

Sathish Kumar
Sathish Kumar

Posted on

JavaScript:

1.Listen for the Click Event:
​First, we attach an event listener to the button element to trigger an action when a user clicks it:

Example:

buttonTag.addEventListener('click', addToCart);

2.Add Item & Update DOM:
​Inside the addToCart function:

​We push the selected product to our cart array.

​We update the UI count dynamically using innerText.

Example:

function addToCart(product) {
cart.push(product);
document.getElementById('cart-count').innerText = cart.length;
}

3.Save Data in LocalStorage:
​To make sure data stays saved in the browser, we use localStorage.setItem:

Example:

localStorage.setItem("cart-item", JSON.stringify(cart));

Top comments (0)