I am attempting to attach an event listener to this HTML element that is being created with an API call
handleProducts()
function handleProducts() {
var display = document.getElementById("display")
var url = "http://127.0.0.1:8000/api/product/"
fetch(url)
.then((resp) => resp.json())
.then(function (data) {
console.log(data)
var products = data
for (var i in products) {
var product = `
<div class="col-lg-4">
<img class="thumbnail" src="${products[i].img}" alt="">
<div class="box-element product">
<h6><strong>${products[i].title}</strong></h6>
<hr>
<button data-product=${products[i].id} data-action = "add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>
<a class="btn btn-outline-success" href="">View</a>
<h4 class="price">${products[i].price}</h4>
</div>
</div>
`
display.insertAdjacentHTML('beforeend', product)
}
})
}
function handleAddToCart(){
var updateBtns = document.getElementsByClassName("update-cart")
console.log(updateBtns)
for (var y = 0; y < updateBtns.length; y++) {
updateBtns[y].addEventListener("click", function () {
console.log("Clicked")
})
}
}
handleAddToCart()
I have included the entire code as there may be additional requirements when attaching an event listener to this type of HTML structure. The issue is that clicking the button does not trigger the 'Clicked' message in the console. Any suggestions?