Home > Blockchain >  how do attach events on dynamically loaded HTML elements with jquery?
how do attach events on dynamically loaded HTML elements with jquery?

Time:11-23

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 >\
         <div >\
           <div >'  name   '</div>\
           <img src="'   imgSrc   '" alt="'   name   '">\
           <div >\
             <h2>'   price   '</h2>\
             <div >\
               <button type="button" id="cart' id '" >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?

CodePudding user response:

Add event handler after html markups has been already added. Something like this:

function loadCard(id, name, imgSrc, price) {
      var template =
         '<div >\
         <div >\
           <div >'  name   '</div>\
           <img src="'   imgSrc   '" alt="'   name   '">\
           <div >\
             <h2>'   price   '</h2>\
             <div >\
               <button type="button" id="cart' id '" >Add to cart</button>\
             </div>\
           </div>\
         </div>\
       </div>' ;

      

   $("#cardContainer").html( template);
   $(".add-card").off("click").click( function(){
      alert ("added to cart");
   });
   }

CodePudding user response:

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:

$("#productList").on("click", ".addToCart", function() {});

This listens for any click event within the DOM element with id productList, it then checks if the element clicked on has the class addToCart 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 id productList.

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.

// Add click event listener to product list wrapper
$("#productList").on("click", ".addToCart", function() {

  // Move up DOM tree to nearest element with .product
  prod = $(this).closest(".product");

  // Store product ID and name
  prodId = prod.attr("data-product-id");
  prodTitle = prod.attr("data-product-name");

  // Add to cart
  // You should think about quantity management etc
  $('#cart').append("<li data-product-id='"   prodId   "'>"   prodTitle   "</li>");


})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <h4>Shopping Cart</h4>
  <ul id='cart'>
  </ul>
</div>

<div id='productList'>
  <h4>Product List</h4>
  <div class='product' data-product-id='prod1' data-product-name='Product One'>
    <h6>Product One</h6>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vulputate interdum tellus sed venenatis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    <button class='addToCart'>Add to cart</button>
  </div>
  <div class='product' data-product-id='prod2' data-product-name='Product Two'>
    <h6>Product Two</h6>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vulputate interdum tellus sed venenatis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
    <button class='addToCart'>Add to cart</button>
  </div>
</div>

  • Related