This is an add-to-cart function. So basically when I pressed the add cart button, it will show the number at the cart icon there. But it doesn't work at all at the first click, but the second click is functioning well.
//cart function
function cartAdd() {
let cart = document.querySelector('.cart');
let add = document.querySelectorAll('.add');
for (let but of add) {
cart.setAttribute('data-count', 0);
but.onclick = () => {
let item = Number(cart.getAttribute('data-count') || 0);
cart.setAttribute('data-count', item + 1);
cart.classList.add('on');
}
}
}
.cart i {
position: relative;
font-size: 30px;
cursor: pointer;
margin: 0px 10px;
top: 18PX;
}
.cart::after {
position: absolute;
content: attr(data-count);
width: 15px;
height: 15px;
font-size: 12px;
border-radius: 15px;
text-align: center;
background-color: red;
color: white;
cursor: pointer;
z-index: 1;
opacity: 0;
}
.cart.on::after {
opacity: 1;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<li class="cart"> <i class="fa fa-shopping-cart"></i></li>
<button class="add" onclick="cartAdd()">Add-cart</button>
I have used console.log('hi') inside the but.onclick but it also won't show the 'hi' for the first click.