I’m trying to make an add to cart function on products that are on cards which are loaded dynamically. I have buttons of class add-cart. I am trying to append the products to a UL on click, but testing my code with a simple alert. Here’s my HTML:
function loadCard(id, name, imgSrc, price) {
var template =
'<div class="pork-items col-lg-3 col-md-4 col-sm-6">
<div class="card h-100">
<div class="card-header">'+ name + '</div>
<img src="' + imgSrc + '" alt="' + name + '">
<div class="card-body">
<h2>' + price + '</h2>
<div class="d-grid gap-2">
<button type="button" id="cart'+id+'" class="add-cart btn btn-lg btn-danger">Add to cart</button>
</div>
</div>
</div>
</div>' ;
var cardContainer = document.getElementById('cardContainer');
cardContainer.innerHTML += template;
}
And this is what I’ve tried so far with jquery. Simply trying to get it to alert before I actually make the cart do something meaningful:
$(document).ready(function(){
$(document).on('click', '.add-cart', function(){
alert ("added to cart");
})
});
The buttons don’t respond the way I want them do. Anybody know the solution for this?
2
Answers
Add event handler after html markups has been already added. Something like this:
I would add an event listener to the div containing your products like below, although the products are not dynamically created this will work for dynamically created products if they are within the product listing div.
The problem is that when you create your event listener the dynamically created products do not exist yet, by adding your event listener to a DOM element that exists on initial load you can avoid this issue. For instance:
This listens for any
click
event within the DOM element with idproductList
, it then checks if the element clicked on has the classaddToCart
and if it does then it will run the function. The elements with.addToCart
do not need to exist when this code is initialised, only the parent div with idproductList
.You could attach this to your
body
but then you will have performance issues, you don’t want to check EVERY click to see if it is a request to add an item to the cart. You should find the most specific element within which all the product cards will sit.The example is fully commented.