Saturday, 24 July 2021

Why do I have to trigger a click event twice to get the proper dataLayer to fire?

Context

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 "Remove from Cart" event.

Issue Description

The initial issue was that the "Remove from Cart" event data layer push never fired because the cart page reloaded to show the updated cart prior to the push.

With the code below, I am now able to get the "Remove from Cart" event to fire, BUT it only fires on the 2nd click of the remove icon.

Question

How do I get the "Remove from Cart" event push to fire on the initial click of the remove icon prior to the cart reload?

JS/Liquid Helper File

Removed unnecessary code for brevity.

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 & 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*="/cart/change"]'],
            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 > 0){
                    values.push(objs);
                    if(key in outputObject){
                        values.push(outputObject[key]);
                        outputObject[key] = values.join(", ");
                    }else{
                        outputObject[key] = values.join(", ");
                    }
                }
            }
        };

        applyBindings(customBindings, __DL__);
        applyBindings(defaultBindings, __DL__);

        /**********************
        * DATALAYER SECTIONS
        ***********************/

                /** DATALAYER: Cart View
                * Fire anytime a user views their cart (non-dynamic) */
                

                            /**********************
                            * 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 > 0){
                                            dataLayer.push(cart);
                                            if (__DL__.debug) {
                                                console.log("Cart"+" :"+JSON.stringify(cart, null, " "));
                                            }
                                        }
                                    });
                                }

                                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 > 0) {
                                                    // check visible selectors
                                                    clearInterval(cartCheck);
                                                    mapJSONcartData();
                                                    $(__DL__.removeCartTrigger).on('click', function (event) {
                                                        // remove from cart
                                                        var link = $(this).attr("href");
                                                        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("Cart"+" :"+JSON.stringify(removeFromCart, null, " "));
                                                            }
                                                        });
                                                    });
                                                }
                                            }, 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 >= 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("Add to Cart"+" :"+JSON.stringify(product, null, " "));
                                    }

                                    // if dynamic cart is TRUE
                                    if (__DL__.dynamicCart) {
                                        console.log("dynamic");
                                        var cartCheck = setInterval(function () {
                                            // begin check interval
                                            if ($(__DL__.cartVisableSelector).length > 0) {
                                                // check visible selectors
                                                clearInterval(cartCheck);
                                                mapJSONcartData();
                                                $(__DL__.removeCartTrigger).on('click', function (event) {
                                                    // remove from cart
                                                    var link = $(this).attr("href");
                                                    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("Cart"+" :"+JSON.stringify(removeFromCart, null, " "));
                                                        }
                                                    });
                                                });
                                            }
                                        }, 500);
                                    }
                                }

                                $(document).on('click', __DL__.cartTriggers, function() {
                                    __DL__addtocart();
                                });

                                }); // document ready
                            }
                        }, 500);

Remove from Cart Link

<a href="#" data-href="/cart/change?line=1&amp;quantity=0" class="tests cart-item__remove icon-fallback">
    <i class="icon icon--close" aria-hidden="true"> </i>
    <span class="icon-fallback__text">Remove</span>
</a>

Initial Data Layer Push (1st Remove from Cart Link Click)

{
  event: "Cart",
  gtm: {uniqueEventId: XXX, start: XXXXXXX},
  logState: "Logged Out",
  firstLog: false,
  customerEmail: null,
  timestamp: 1626795802651,
  currency: "USD",
  pageType: "Cart",
  products: [
    {
      id: XXXX,
      sku: "XXX",
      variant: XXX,
      name: "XXXX",
      price: 20,
      quantity: 1
    }
  ],
  necessaryTags: true,
  performanceTags: true,
  functionalTags: true,
  targettingTags: true
}

Second Data Layer Push (2nd Remove from Cart Link Click)

{
  event: "Remove from Cart",
  gtm: {uniqueEventId: XXX, start: XXXXXX},
  logState: "Logged Out",
  firstLog: false,
  timestamp: 1626796193806,
  currency: "USD",
  pageType: "Remove from Cart",
  products: [
    {
      id: XXXX,
      sku: "XXX",
      variant: XXX,
      name: "XXXX",
      price: 20,
      quantity: 1
    }
  ],
  necessaryTags: true,
  performanceTags: false,
  functionalTags: false,
  targettingTags: false
}

I appreciate your help in advance!



from Why do I have to trigger a click event twice to get the proper dataLayer to fire?

No comments:

Post a Comment