0

I have a page of dynamically loaded elements that respond as they should with click events. When I click on one of the elements the data loads into a shopping cart and that what's not responding. Specifically, it's a trash icon.

The window does not refresh when I click on the item to send it to the cart.

This sends the data to the cart. It is not wrapped in $(document).ready() fyi

$("#product-add-to-cart").click(e => {

      let cart_data = ""
      let modal_data = ""

      const cartImg = image1
      const itemTitle = title
      const subTotal = parseFloat(subtotal.innerText)

      // --------- Added to Cart -------------
      cart_data += `<img src="../${cartImg}" alt="cart-img" id="cart-image">`
      cart_data += '<div class="item-title">'
      cart_data += `<span id="cart-item-title" class="font-weight-bold mb-0">${itemTitle}</span>`
      cart_data += '</div>'
      cart_data += '<div>'
      cart_data += '<span>$</span>'
      cart_data += `<span id="cart-item-price" class="cart-item-price" class="mb-0">${subTotal}</span>`
      cart_data += '</div>'
      cart_data += '<a href="#" id="cart-item-remove">'
      cart_data += '<ion-icon name="trash"></ion-icon>'
      cart_data += '</a>'

      $(".cart-item").html(cart_data)

These are the functions I've tried. This is in a different JS file but I tried the functions in both files and it was the same.

$("#cart-item-remove").click((e) => {
    console.log(e.target)
  })
$("#cart-item-remove").on("click", "a", function(e){  
    console.log('delete')
  })

I found other similar threads and one suggested .on() but it has an additional argument and I wasn't sure how to apply it.

Jeff S
  • 109
  • 2
  • 13
  • 2
    Delegate event bindings are added to a static parent of the dynamic elements. Not on the dynamic children. You cannot add an event binding to dynamic elements, because they are dynamic. They don't exist until they exist. – Taplar Jan 03 '20 at 20:33
  • 1
    Dynamically loaded elements are not registered with jQuery since your click event won't work, but you can make it work by listing click event on parent element of Dynamic elements are loaded, using "on" method – Yogesh Patel Jan 03 '20 at 20:36
  • Now I understand. Got to work! thanks – Jeff S Jan 03 '20 at 22:38

0 Answers0