title: Why do I have to trigger a click event twice to get the proper dataLayer to fire?
body: <p><strong>Context</strong></p>
  <p>I am attempting to push events to the data layer on a Shopify site. I'm utilizing a liquid file that combines liquid and JS code to extract appropriate data from the site to push to the data layer. All of the events are firing properly with the exception of the &quot;Remove from Cart&quot; event.</p>
  <p><strong>Issue Description</strong></p>
  <p>The initial issue was that the &quot;Remove from Cart&quot; event data layer push never fired because the cart page reloaded to show the updated cart prior to the push.</p>
  <p>With the code below, I am now able to get the &quot;Remove from Cart&quot; event to fire, <strong>BUT it only fires on the 2nd click of the remove icon.</strong></p>
  <p><strong>Question</strong></p>
  <p>How do I get the &quot;Remove from Cart&quot; event push to fire on the initial click of the remove icon prior to the cart reload?</p>
  <p><strong>JS/Liquid Helper File</strong></p>
  <p>Removed unnecessary code for brevity.</p>
  <pre><code>if(!window.jQuery){
      var jqueryScript = document.createElement('script');
      jqueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js');
      document.head.appendChild(jqueryScript);
  }
  
  __DL__jQueryinterval = setInterval(function(){
      // wait for jQuery to load &amp; run script after jQuery has loaded
      if(window.jQuery){
          
          /**********************
          * DYNAMIC DEPENDENCIES
          ***********************/
  
          __DL__ = {
              dynamicCart: true,  // if cart is dynamic (meaning no refresh on cart add) set to true
              debug: true, // if true, console messages will be displayed
              cart:  true,
              removeCart: true
          };
  
          customBindings = {
              cartTriggers: [],
              viewCart: [],
              removeCartTrigger: [],
          };
  
          /* DO NOT EDIT */
          defaultBindings = {
              //removeCartTrigger: ['[href*=&quot;/cart/change&quot;]'],
              removeCartTrigger: ['.tests'],
          };
  
          // stitch bindings
          objectArray = customBindings;
          outputObject = __DL__;
  
          applyBindings = function(objectArray, outputObject){
              for (var x in objectArray) {
                  var key = x;
                  var objs = objectArray[x];
                  values = [];
                  if(objs.length &gt; 0){
                      values.push(objs);
                      if(key in outputObject){
                          values.push(outputObject[key]);
                          outputObject[key] = values.join(&quot;, &quot;);
                      }else{
                          outputObject[key] = values.join(&quot;, &quot;);
                      }
                  }
              }
          };
  
          applyBindings(customBindings, __DL__);
          applyBindings(defaultBindings, __DL__);
  
          /**********************
          * DATALAYER SECTIONS
          ***********************/
  
                  /** DATALAYER: Cart View
                  * Fire anytime a user views their cart (non-dynamic) */
                  {% if template contains 'cart' %}
                  var cart = {
                      'products':[{% for line_item in cart.items %}{
                          'id'       : {{line_item.product_id | json}},
                          'sku'      : {{line_item.sku | json}},
                          'variant'  : {{line_item.variant_id | json}},
                          'name'     : {{line_item.title | json}},
                          'price'    : {{line_item.price | money_without_currency | remove: &quot;,&quot; | json}},
                          'quantity' : {{line_item.quantity | json}}
                      },{% endfor %}],
                      'pageType' : 'Cart',
                      'event'    : 'Cart'
                  };
  
                  dataLayer.push(cart);
  
                  if(__DL__.debug){
                      console.log(&quot;Cart&quot;+&quot; :&quot;+JSON.stringify(cart, null, &quot; &quot;));
                  }
  
                  __DL__.cart = cart.products;
  
                  $(__DL__.removeCartTrigger).on('click', function (event) {
                      setTimeout(function(){
                         //const goTo = $(this).attr(&quot;data-href&quot;);  // store anchor href
                          // remove from cart
                          jQuery.getJSON(&quot;/cart&quot;, function (response) {
                              // get Json response
                              __DL__.removeCart = response;
                              var removeFromCart = {
                                  'products': __DL__.removeCart.items.map(function (line_item) {
                                      return {
                                          'id'       : line_item.product_id,
                                          'sku'      : line_item.sku,
                                          'variant'  : line_item.variant_id,
                                          'name'     : line_item.title,
                                          'price'    : (line_item.price/100),
                                          'quantity' : line_item.quantity
                                      }
                                  }),
                                  'pageType' : 'Remove from Cart',
                                  'event'    : 'Remove from Cart'
                              };
                              __DL__.removeCart = removeFromCart;
  
                              var cartIDs = [];
                              var removeIDs = [];
                              var removeCart = [];
  
                              // remove from cart logic
                              for(var i=__DL__.cart.length-1;i&gt;=0;i--){var x=parseFloat(__DL__.cart[i].variant);cartIDs.push(x)}for(var i=__DL__.removeCart.products.length-1;i&gt;=0;i--){var x=parseFloat(__DL__.removeCart.products[i].variant);removeIDs.push(x)}function arr_diff(b,c){var a=[],diff=[];for(var i=0;i&lt;b.length;i++){a[b[i]]=true}for(var i=0;i&lt;c.length;i++){if(a[c[i]]){delete a[c[i]]}else{a[c[i]]=true}}for(var k in a){diff.push(k)}return diff};var x=arr_diff(cartIDs,removeIDs)[0];for(var i=__DL__.cart.length-1;i&gt;=0;i--){if(__DL__.cart[i].variant==x){removeCart.push(__DL__.cart[i])}}
  
                              dataLayer.push(removeCart);
  
                              if (__DL__.debug) {
                                  console.log(&quot;Item Removed from Cart&quot;+&quot; :&quot;+JSON.stringify(removeCart, null, &quot; &quot;));
                              }
                          });
                      }, 2000);
                  });
  
                  {% endif %}
  
                              /**********************
                              * DATALAYER EVENT BINDINGS
                              ***********************/
  
                              /** DATALAYER:
                              * Add to Cart / Dynamic Cart View
                              * Fire all pages trigger after all additional dataLayers have loaded. */
  
                              $(document).ready(function() {
  
                                  /** DATALAYER: Cart */
  
                                  // stage cart data
                                  function mapJSONcartData(){
                                      jQuery.getJSON('/cart.js', function (response) {
                                          // get Json response
                                          __DL__.cart = response;
                                          var cart = {
                                              'products': __DL__.cart.items.map(function (line_item) {
                                                  return {
                                                      'id'       : line_item.id,
                                                      'sku'      : line_item.sku,
                                                      'variant'  : line_item.variant_id,
                                                      'name'     : line_item.title,
                                                      'price'    : (line_item.price/100),
                                                      'quantity' : line_item.quantity
                                                  }
                                              }),
                                              'pageType' : 'Cart',
                                              'event'    : 'Cart'
                                          };
                                          if(cart.products.length &gt; 0){
                                              dataLayer.push(cart);
                                              if (__DL__.debug) {
                                                  console.log(&quot;Cart&quot;+&quot; :&quot;+JSON.stringify(cart, null, &quot; &quot;));
                                              }
                                          }
                                      });
                                  }
  
                                  viewcartfire = 0;
  
                                  // view cart
                                  $(__DL__.viewCart).on('click', function (event) {
                                      if(viewcartfire !== 1){
                                          viewcartfire = 1;
                                          // if dynamic cart is TRUE
                                          if (__DL__.dynamicCart) {
                                              cartCheck = setInterval(function () {
                                                  // begin check interval
                                                  if ($(__DL__.cartVisableSelector).length &gt; 0) {
                                                      // check visible selectors
                                                      clearInterval(cartCheck);
                                                      mapJSONcartData();
                                                      $(__DL__.removeCartTrigger).on('click', function (event) {
                                                          // remove from cart
                                                          var link = $(this).attr(&quot;href&quot;);
                                                          jQuery.getJSON(link, function (response) {
                                                              // get Json response
                                                              __DL__.removeCart = response;
                                                              var removeFromCart = {
                                                                  'products': __DL__.removeCart.items.map(function (line_item) {
                                                                      return {
                                                                          'id'       : line_item.id,
                                                                          'sku'      : line_item.sku,
                                                                          'variant'  : line_item.variant_id,
                                                                          'name'     : line_item.title,
                                                                          'price'    : (line_item.price/100),
                                                                          'quantity' : line_item.quantity
                                                                      }
                                                                  }),
                                                                  'pageType' : 'Remove from Cart',
                                                                  'event'    : 'Remove from Cart'
                                                              };
                                                              dataLayer.push(removeFromCart);
                                                              if (__DL__.debug) {
                                                                  console.log(&quot;Cart&quot;+&quot; :&quot;+JSON.stringify(removeFromCart, null, &quot; &quot;));
                                                              }
                                                          });
                                                      });
                                                  }
                                              }, 500);
                                          }
                                      }
                                  });
  
                                  // add to cart
                                  jQuery.getJSON('/cart.js', function (response) {
                                      // get Json response
                                      __DL__.cart = response;
                                      var cart = {
                                          'products': __DL__.cart.items.map(function (line_item) {
                                              return {
                                                  'id'       : line_item.id,
                                                  'sku'      : line_item.sku,
                                                  'variant'  : line_item.variant_id,
                                                  'name'     : line_item.title,
                                                  'price'    : (line_item.price/100),
                                                  'quantity' : line_item.quantity
                                              }
                                          })
                                      }
                                      __DL__.cart = cart;
                                      collection_cartIDs = [];
                                      collection_matchIDs = [];
                                      collection_addtocart = [];
                                      for (var i = __DL__.cart.products.length - 1; i &gt;= 0; i--) {
                                          var x = parseFloat(__DL__.cart.products[i].variant);
                                          collection_cartIDs.push(x);
                                      }
                                  });
  
                                  function __DL__addtocart(){
  
  
  
                                      dataLayer.push(product, {
                                          'pageType' : 'Add to Cart',
                                          'event'    : 'Add to Cart'
                                      });
  
                                      if (__DL__.debug) {
                                          console.log(&quot;Add to Cart&quot;+&quot; :&quot;+JSON.stringify(product, null, &quot; &quot;));
                                      }
  
                                      // if dynamic cart is TRUE
                                      if (__DL__.dynamicCart) {
                                          console.log(&quot;dynamic&quot;);
                                          var cartCheck = setInterval(function () {
                                              // begin check interval
                                              if ($(__DL__.cartVisableSelector).length &gt; 0) {
                                                  // check visible selectors
                                                  clearInterval(cartCheck);
                                                  mapJSONcartData();
                                                  $(__DL__.removeCartTrigger).on('click', function (event) {
                                                      // remove from cart
                                                      var link = $(this).attr(&quot;href&quot;);
                                                      jQuery.getJSON(link, function (response) {
                                                          // get Json response
                                                          __DL__.removeCart = response;
                                                          var removeFromCart = {
                                                              'products': __DL__.removeCart.items.map(function (line_item) {
                                                                  return {
                                                                      'id'       : line_item.id,
                                                                      'sku'      : line_item.sku,
                                                                      'variant'  : line_item.variant_id,
                                                                      'name'     : line_item.title,
                                                                      'price'    : (line_item.price/100),
                                                                      'quantity' : line_item.quantity
                                                                  }
                                                              }),
                                                              'pageType' : 'Remove from Cart',
                                                              'event'    : 'Remove from Cart'
                                                          };
                                                          dataLayer.push(removeFromCart);
                                                          if (__DL__.debug) {
                                                              console.log(&quot;Cart&quot;+&quot; :&quot;+JSON.stringify(removeFromCart, null, &quot; &quot;));
                                                          }
                                                      });
                                                  });
                                              }
                                          }, 500);
                                      }
                                  }
  
                                  $(document).on('click', __DL__.cartTriggers, function() {
                                      __DL__addtocart();
                                  });
  
                                  }); // document ready
                              }
                          }, 500);
  </code></pre>
  <p><strong>Remove from Cart Link</strong></p>
  <pre><code>&lt;a href=&quot;#&quot; data-href=&quot;/cart/change?line=1&amp;amp;quantity=0&quot; class=&quot;tests cart-item__remove icon-fallback&quot;&gt;
      &lt;i class=&quot;icon icon--close&quot; aria-hidden=&quot;true&quot;&gt; &lt;/i&gt;
      &lt;span class=&quot;icon-fallback__text&quot;&gt;Remove&lt;/span&gt;
  &lt;/a&gt;
  </code></pre>
  <p><strong>Initial Data Layer Push (1st Remove from Cart Link Click)</strong></p>
  <pre><code>{
    event: &quot;Cart&quot;,
    gtm: {uniqueEventId: XXX, start: XXXXXXX},
    logState: &quot;Logged Out&quot;,
    firstLog: false,
    customerEmail: null,
    timestamp: 1626795802651,
    currency: &quot;USD&quot;,
    pageType: &quot;Cart&quot;,
    products: [
      {
        id: XXXX,
        sku: &quot;XXX&quot;,
        variant: XXX,
        name: &quot;XXXX&quot;,
        price: 20,
        quantity: 1
      }
    ],
    necessaryTags: true,
    performanceTags: true,
    functionalTags: true,
    targettingTags: true
  }
  </code></pre>
  <p><strong>Second Data Layer Push (2nd Remove from Cart Link Click)</strong></p>
  <pre><code>{
    event: &quot;Remove from Cart&quot;,
    gtm: {uniqueEventId: XXX, start: XXXXXX},
    logState: &quot;Logged Out&quot;,
    firstLog: false,
    timestamp: 1626796193806,
    currency: &quot;USD&quot;,
    pageType: &quot;Remove from Cart&quot;,
    products: [
      {
        id: XXXX,
        sku: &quot;XXX&quot;,
        variant: XXX,
        name: &quot;XXXX&quot;,
        price: 20,
        quantity: 1
      }
    ],
    necessaryTags: true,
    performanceTags: false,
    functionalTags: false,
    targettingTags: false
  }
  </code></pre>
  <p>I appreciate your help in advance!</p>