Javascript addEventListener and click function not working for me on Anchor tag <a>

i hava also tried jquery but not worked for me i dont know why. this is my javascript code

'''
var cartLinks = document.getElementsByClassName('update-cart')
console.log(cartLinks)



for (var i = 0; i < cartLinks.length; i++) {
    console.log('enterd in loop')
    cartLinks[i].addEventListener("click", function () {
        console.log('print...')
        var productId = this.dataset.product
        console.log(productId)
    })
}
'''

this is the tag where i want to use. '''

 <a href="#"  data-product={{product.id}} data-action="add" data-toggle="tooltip" class ="update-cart" title="Add To Cart"><i class="ion-bag"></i></a>
'''

this is how i used script in my code. '''

<body>
   some code

   some scripts
   <script src="{% static 'js/cart.js' %}"></script>
</body>

'''

Hi your code is as follow

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link 
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" 
rel="stylesheet" integrity="sha3841BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" 
crossorigin="anonymous">
</head>

<body>
hello
<a href="#" data-product=1 data-action="add" data-toggle="tooltip" class="btn btn-primary update-cart" title="Add To Cart">text1</a>
<a href="#" data-product=2 data-action="add" data-toggle="tooltip" class="btn btn-secondary update-cart" title="Add To Cart">text1</a>
<a href="#" data-product=3 data-action="add" data-toggle="tooltip" class="btn btn-success update-cart" title="Add To Cart">text1</a>
<a href="#" data-product=4 data-action="add" data-toggle="tooltip" class="btn btn-danger update-cart" title="Add To Cart">text1</a>
<script src="cart.js"></script>
</body>

</html>

cart.js
var cartLinks = document.getElementsByClassName('update-cart')
console.log(cartLinks)

for (var i = 0; i < cartLinks.length; i++) {
console.log('enterd in loop')
cartLinks[i].addEventListener("click", function() {
    console.log('print...')
    var productId = this.dataset.product
    console.log(productId)
})

}

add cart.js file at the end. Your javascript file load first then the anchor tag. That is only problem I have found...

Back to Top