Data attribute is returning undefined in JQuery

Viewed 199

This was working for me before but stopped working. I am trying grab the data attribute so that I can add to cart via AJAX.

UPDATE: My goal is to get the data from the data-variant-id attribute so that I can add to cart via Shopify's AJAX API. Previously, I had a button that said ADD TO CART and that worked well. All of a sudden, the button stopped working when I added an icon tag.

This is the snippet:

// Fake Shopify
const Shopify = {
  addItem (id, qty, cb) {
    console.log("Shopify.addItem - id: %s, qty: %i", id, qty)
    setTimeout(cb, 200)
  }
}

const refreshCart = () => console.log("refreshCart")

$('[data-variant-id]').each(function() {
  $(this).on('click', function(e) {
    e.preventDefault();
    var button = e.target
    var variantId = button.dataset.variantId

    console.log('variantId', variantId);

    // Add Item to cart
    Shopify.addItem(variantId, 1, function() {

      // Now its added. lets refresh the cart drawer
      refreshCart();

      // Now its refreshed. Lets open the drawer
      $('[data-drawer-trigger]')[0].click();
    })
  })
})
@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css");
[data-drawer-trigger] { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<button data-variant-id="40173189300410" value="Add to Cart" class="btn-icon"><i class="fas fa-shopping-cart"></i></button>

<button data-drawer-trigger>Drawer Trigger Button</button>

1 Answers
var button = e.target

This is your problem.

When you click on the button, you're most likely actually clicking on the <i> which is the element identified by e.target.

The event bubbles up to the button which triggers your event handler but then your <i> does not have any data-* attributes so button.dataset.variantId is undefined.

The simple solution is to use jQuery's this binding in the event handler which binds to the event currentTarget (the element you added the handler on). You also don't need .each()

$('button[data-variant-id]').on("click", function(e) {
  e.preventDefault()
  const variantId = this.dataset.variantId // note `this`

  console.log('variantId', variantId);

  // Add Item to cart
  Shopify.addItem(variantId, 1, function() {

    // Now its added. lets refresh the cart drawer
    refreshCart();

    // Now it's refreshed. Lets open the drawer
    $('[data-drawer-trigger]').eq(0).click(); // using `.eq(0)` is safer
  })
})

Also, your icon should be

<i class="fas fa-shopping-cart"></i>

Note the fas class name, not far.

Related