[text] code

Viewer

  1. <script>
  2. /**********************
  3. * DATALAYER ARCHITECTURE: SHOPIFY 
  4. * DEFINITION: A data layer helps you collect more accurate analytics data, that in turn allows you to better understand what potential buyers are doing on your website and where you can make improvements. It also reduces the time to implement marketing tags on a website, and reduces the need for IT involvement, leaving them to get on with implementing new features and fixing bugs.
  5.  
  6. * RESOURCES:
  7. * http://www.datalayerdoctor.com/a-gentle-introduction-to-the-data-layer-for-digital-marketers/
  8. * http://www.simoahava.com/analytics/data-layer/
  9.  
  10. * EXTERNAL DEPENDENCIES:
  11. * jQuery
  12. * jQuery Cookie Plugin v1.4.1 - https://github.com/carhartl/jquery-cookie
  13. * cartjs - https://github.com/discolabs/cartjs
  14.  
  15. * DataLayer Architecture: Shopify v1.2
  16. * COPYRIGHT 2021
  17. * LICENSES: MIT ( https://opensource.org/licenses/MIT )
  18. */
  19.  
  20. /**********************
  21. * PRELOADS 
  22. * load jquery if it doesn't exist
  23. ***********************/ 
  24.  
  25. if(!window.jQuery){
  26.     var jqueryScript = document.createElement('script');
  27.     jqueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js'); 
  28.     document.head.appendChild(jqueryScript); 
  29. }
  30.  
  31. __DL__jQueryinterval = setInterval(function(){
  32.     // wait for jQuery to load & run script after jQuery has loaded
  33.     if(window.jQuery){
  34.         // search parameters
  35.         getURLParams = function(name, url){
  36.             if (!url) url = window.location.href;
  37.             name = name.replace(/[\[\]]/g, "\\$&");
  38.             var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
  39.             results = regex.exec(url);
  40.             if (!results) return null;
  41.             if (!results[2]) return '';
  42.             return decodeURIComponent(results[2].replace(/\+/g, " "));
  43.         };
  44.         
  45.         /**********************
  46.         * DYNAMIC DEPENDENCIES
  47.         ***********************/
  48.         
  49.         __DL__ = {
  50.             dynamicCart: true,  // if cart is dynamic (meaning no refresh on cart add) set to true
  51.             debug: true, // if true, console messages will be displayed
  52.             cart: null,
  53.             wishlist: null,
  54.             removeCart: null
  55.         };
  56.         
  57.         customBindings = {
  58.             cartTriggers: [],
  59.             viewCart: [],
  60.             removeCartTrigger: [],
  61.             cartVisableSelector: [],
  62.             promoSubscriptionsSelectors: [],
  63.             promoSuccess: [],
  64.             ctaSelectors: [],
  65.             newsletterSelectors: [],
  66.             newsletterSuccess: [],
  67.             searchPage: [],
  68.             wishlistSelector: [],
  69.             removeWishlist: [],
  70.             wishlistPage: [],
  71.             searchTermQuery: [getURLParams('q')], // replace var with correct query
  72.         };
  73.         
  74.         /* DO NOT EDIT */
  75.         defaultBindings = {
  76.             cartTriggers: ['form[action="/cart/add"] [type="submit"],.add-to-cart,.cart-btn'],
  77.             viewCart: ['form[action="/cart"],.my-cart,.trigger-cart,#mobileCart'],
  78.             removeCartTrigger: ['[href*="/cart/change"]'],
  79.             cartVisableSelector: ['.inlinecart.is-active,.inline-cart.is-active'],
  80.             promoSubscriptionsSelectors: [],
  81.             promoSuccess: [],
  82.             ctaSelectors: [],
  83.             newsletterSelectors: ['input.contact_email'],
  84.             newsletterSuccess: ['.success_message'],
  85.             searchPage: ['search'],
  86.             wishlistSelector: [],
  87.             removeWishlist: [],
  88.             wishlistPage: []
  89.         };
  90.         
  91.         // stitch bindings
  92.         objectArray = customBindings;
  93.         outputObject = __DL__;
  94.         
  95.         applyBindings = function(objectArray, outputObject){
  96.             for (var x in objectArray) {  
  97.                 var key = x;
  98.                 var objs = objectArray[x]; 
  99.                 values = [];    
  100.                 if(objs.length > 0){    
  101.                     values.push(objs);
  102.                     if(key in outputObject){              
  103.                         values.push(outputObject[key]); 
  104.                         outputObject[key] = values.join(", "); 
  105.                     }else{        
  106.                         outputObject[key] = values.join(", ");
  107.                     }   
  108.                 }  
  109.             }
  110.         };
  111.         
  112.         applyBindings(customBindings, __DL__);
  113.         applyBindings(defaultBindings, __DL__);
  114.         
  115.         /**********************
  116.         * PREREQUISITE LIBRARIES 
  117.         ***********************/
  118.         
  119.         clearInterval(__DL__jQueryinterval);
  120.         
  121.         // jquery-cookies.js
  122.         if(typeof $.cookie!==undefined){(function(a){if(typeof define==='function'&&define.amd){define(['jquery'],a)}else if(typeof exports==='object'){module.exports=a(require('jquery'))}else{a(jQuery)}}(function($){var g=/\+/g;function encode(s){return h.raw?s:encodeURIComponent(s)}function decode(s){return h.raw?s:decodeURIComponent(s)}function stringifyCookieValue(a){return encode(h.json?JSON.stringify(a):String(a))}function parseCookieValue(s){if(s.indexOf('"')===0){s=s.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,'\\')}try{s=decodeURIComponent(s.replace(g,' '));return h.json?JSON.parse(s):s}catch(e){}}function read(s,a){var b=h.raw?s:parseCookieValue(s);return $.isFunction(a)?a(b):b}var h=$.cookie=function(a,b,c){if(arguments.length>1&&!$.isFunction(b)){c=$.extend({},h.defaults,c);if(typeof c.expires==='number'){var d=c.expires,t=c.expires=new Date();t.setMilliseconds(t.getMilliseconds()+d*864e+5)}return(document.cookie=[encode(a),'=',stringifyCookieValue(b),c.expires?'; expires='+c.expires.toUTCString():'',c.path?'; path='+c.path:'',c.domain?'; domain='+c.domain:'',c.secure?'; secure':''].join(''))}var e=a?undefined:{},cookies=document.cookie?document.cookie.split('; '):[],i=0,l=cookies.length;for(;i<l;i++){var f=cookies[i].split('='),name=decode(f.shift()),cookie=f.join('=');if(a===name){e=read(cookie,b);break}if(!a&&(cookie=read(cookie))!==undefined){e[name]=cookie}}return e};h.defaults={};$.removeCookie=function(a,b){$.cookie(a,'',$.extend({},b,{expires:-1}));return!$.cookie(a)}}))}
  123.         
  124.         /**********************
  125.         * Begin dataLayer Build 
  126.         ***********************/
  127.         
  128.         /**
  129.         * DEBUG
  130.         * Set to true or false to display messages to the console
  131.         */
  132.         if(__DL__.debug){
  133.             console.log('=====================\n| DATALAYER SHOPIFY |\n---------------------');
  134.             console.log('Page Template: {{ template }}');
  135.         }
  136.         
  137.         window.dataLayer = window.dataLayer || [];  // init data layer if doesn't already exist
  138.         dataLayer.push({'event': 'Begin DataLayer'}); // begin datalayer
  139.         
  140.         var template = "{{template}}"; 
  141.         
  142.         /**
  143.         * Landing Page Cookie
  144.         * 1. Detect if user just landed on the site
  145.         * 2. Only fires if Page Title matches website */
  146.         
  147.         $.cookie.raw = true;
  148.         if ($.cookie('landingPage') === undefined || $.cookie('landingPage').length === 0) {
  149.             var landingPage = true;
  150.             $.cookie('landingPage', unescape);
  151.             $.removeCookie('landingPage', {path: '/'});
  152.             $.cookie('landingPage', 'landed', {path: '/'});
  153.         } else {
  154.             var landingPage = false;
  155.             $.cookie('landingPage', unescape);
  156.             $.removeCookie('landingPage', {path: '/'});
  157.             $.cookie('landingPage', 'refresh', {path: '/'});
  158.         }
  159.         if (__DL__.debug) {
  160.             console.log('Landing Page: ' + landingPage);
  161.         }
  162.         
  163.         /** 
  164.         * Log State Cookie */
  165.         
  166.         {% if customer %}
  167.         var isLoggedIn = true;
  168.         {% else %}
  169.         var isLoggedIn = false;
  170.         {% endif %}
  171.         if (!isLoggedIn) {
  172.             $.cookie('logState', unescape);
  173.             $.removeCookie('logState', {path: '/'});
  174.             $.cookie('logState', 'loggedOut', {path: '/'});
  175.         } else {
  176.             if ($.cookie('logState') === 'loggedOut' || $.cookie('logState') === undefined) {
  177.                 $.cookie('logState', unescape);
  178.                 $.removeCookie('logState', {path: '/'});
  179.                 $.cookie('logState', 'firstLog', {path: '/'});
  180.             } else if ($.cookie('logState') === 'firstLog') {
  181.                 $.cookie('logState', unescape);
  182.                 $.removeCookie('logState', {path: '/'});
  183.                 $.cookie('logState', 'refresh', {path: '/'});
  184.             }
  185.         }
  186.         
  187.         if ($.cookie('logState') === 'firstLog') {
  188.             var firstLog = true;
  189.         } else {
  190.             var firstLog = false;
  191.         }
  192.         
  193.         /**********************
  194.         * DATALAYER SECTIONS 
  195.         ***********************/
  196.         
  197.         /**
  198.         * DATALAYER: Landing Page
  199.         * Fires any time a user first lands on the site. */
  200.         
  201.         if ($.cookie('landingPage') === 'landed') {
  202.             dataLayer.push({
  203.                 'pageType': 'Landing',
  204.                 'event': 'Landing'
  205.             });
  206.             
  207.             if (__DL__.debug) {
  208.                 console.log('DATALAYER: Landing Page fired.');
  209.             }
  210.         }
  211.         
  212.         /** 
  213.         * DATALAYER: Log State
  214.         * 1. Determine if user is logged in or not.
  215.         * 2. Return User specific data. */
  216.         
  217.         var logState = {
  218.             {% if shop.customer_accounts_enabled %}
  219.             {% if customer %}
  220.             'userId'        : {{customer.id | json}},
  221.             'customerEmail' : {{customer.email | json}},
  222.             'logState'      : "Logged In",
  223.             'customerInfo'  : {
  224.                 'firstName'   : {{customer_address.first_name | json}},
  225.                 'lastName'    : {{customer_address.last_name | json}},
  226.                 'address1'    : {{customer_address.address1 | json}},
  227.                 'address2'    : {{customer_address.address2 | json}},
  228.                 'street'      : {{customer_address.street | json}},
  229.                 'city'        : {{customer_address.city | json}},
  230.                 'province'    : {{customer_address.province | json}},
  231.                 'zip'         : {{customer_address.zip | json}},
  232.                 'country'     : {{customer_address.country | json}},
  233.                 'phone'       : {{customer_address.phone | json}},
  234.                 'totalOrders' : {{customer.orders_count | json}},
  235.                 'totalSpent'  : {{customer.total_spent | money_without_currency | remove: "," | json}}
  236.             },
  237.             {% else %}
  238.             'logState' : "Logged Out",
  239.             {% endif %}
  240.             {% endif %}
  241.             'firstLog'      : firstLog,
  242.             'customerEmail' : {{customer.email | json}},
  243.             'timestamp'     : Date.now(),  
  244.             {% if customer.orders_count > 2 %}
  245.             'customerType'       : 'Returning',
  246.             'customerTypeNumber' : '0',
  247.             {% else %}
  248.             'customerType'       : 'New',
  249.             'customerTypeNumber' :'1', 
  250.             {% endif %}
  251.             'shippingInfo' : {
  252.                 'fullName'  : {{checkout.shipping_address.name | json}},
  253.                 'firstName' : {{checkout.shipping_address.first_name | json}},
  254.                 'lastName'  : {{checkout.shipping_address.last_name | json}},
  255.                 'address1'  : {{checkout.shipping_address.address1 | json}},
  256.                 'address2'  : {{checkout.shipping_address.address2 | json}},
  257.                 'street'    : {{checkout.shipping_address.street | json}},
  258.                 'city'      : {{checkout.shipping_address.city | json}},
  259.                 'province'  : {{checkout.shipping_address.province | json}},
  260.                 'zip'       : {{checkout.shipping_address.zip | json}},
  261.                 'country'   : {{checkout.shipping_address.country | json}},
  262.                 'phone'     : {{checkout.shipping_address.phone | json}},
  263.             },
  264.             'billingInfo' : {
  265.                 'fullName'  : {{checkout.billing_address.name | json}},
  266.                 'firstName' : {{checkout.billing_address.first_name | json}},
  267.                 'lastName'  : {{checkout.billing_address.last_name | json}},
  268.                 'address1'  : {{checkout.billing_address.address1 | json}},
  269.                 'address2'  : {{checkout.billing_address.address2 | json}},
  270.                 'street'    : {{checkout.billing_address.street | json}},
  271.                 'city'      : {{checkout.billing_address.city | json}},
  272.                 'province'  : {{checkout.billing_address.province | json}},
  273.                 'zip'       : {{checkout.billing_address.zip | json}},
  274.                 'country'   : {{checkout.billing_address.country | json}},
  275.                 'phone'     : {{checkout.billing_address.phone | json}},
  276.             },
  277.             'checkoutEmail' : {{checkout.email | json}},
  278.             'currency'      : {{shop.currency | json}},
  279.             'pageType'      : 'Log State',
  280.             'event'         : 'Log State'
  281.         }
  282.         
  283.         dataLayer.push(logState);
  284.         if(__DL__.debug){
  285.             console.log("Log State"+" :"+JSON.stringify(logState, null, " "));
  286.         }
  287.         
  288.         /** 
  289.         * DATALAYER: Homepage */
  290.         
  291.         if(document.location.pathname == "/"){
  292.             var homepage = {
  293.                 'pageType' : 'Homepage',
  294.                 'event'    : 'Homepage'
  295.             };
  296.             dataLayer.push(homepage);
  297.             if(__DL__.debug){
  298.                 console.log("Homepage"+" :"+JSON.stringify(homepage, null, " "));
  299.             }
  300.         }
  301.         
  302.         /** 
  303.         * DATALAYER: Blog Articles
  304.         * Fire on Blog Article Pages */
  305.         
  306.         {% if template contains 'article' %}
  307.         var blog = {
  308.             'author'      : {{article.author | json}},
  309.             'title'       : {{article.title | json}},
  310.             'dateCreated' : {{article.created_at | json}},
  311.             'pageType'    : 'Blog',
  312.             'event'       : 'Blog'
  313.         };
  314.         dataLayer.push(blog);
  315.         if(__DL__.debug){
  316.             console.log("Blog"+" :"+JSON.stringify(blog, null, " "));
  317.         }
  318.         {% endif %}
  319.         
  320.         /** DATALAYER: Product List Page (Collections, Category)
  321.         * Fire on all product listing pages. */
  322.         
  323.         {% if template contains 'collection' %}
  324.         var product = {
  325.             'products': [
  326.                 {% for product in collection.products %}{
  327.                     'id'              : {{product.id | json}},
  328.                     'sku'             : {{product.selected_or_first_available_variant.sku | json}},
  329.                     'variantId'       : {{product.selected_or_first_available_variant.id | json}},
  330.                     'productType'     : {{product.type | json}},
  331.                     'name'            : {{product.title | json}},
  332.                     'price'           : {{product.price | money_without_currency | remove: "," | json}},
  333.                     'imageURL'        : "https:{{product.featured_image.src|img_url:'grande'}}", 
  334.                     'productURL'      : '{{shop.secure_url}}{{product.url}}',
  335.                     'brand'           : {{shop.name | json}},
  336.                     'comparePrice'    : {{product.compare_at_price_max | money_without_currency | remove: "," | json}},
  337.                     'categories'      : {{product.collections|map:"title" | json}},
  338.                     'currentCategory' : {{collection.title | json}},
  339.                     'productOptions'  : {
  340.                         {% for option in product.options_with_values %}
  341.                         {% for value in option.values %}
  342.                         {% if option.selected_value == value %}
  343.                         {{option.name | json}} : {{value | json}},
  344.                         {% endif %}
  345.                         {% endfor %}
  346.                         {% endfor %}
  347.                     }
  348.                 },
  349.                 {% endfor %}]
  350.             };
  351.             var collections = {
  352.                 'productList' : {{collection.title | json}},
  353.                 'pageType'    : 'Collection',
  354.                 'event'       : 'Collection'
  355.             };
  356.             dataLayer.push(product);
  357.             dataLayer.push(collections);
  358.             if(__DL__.debug){
  359.                 console.log("Collections"+" :"+JSON.stringify(product, null, " "));
  360.                 console.log("Collections"+" :"+JSON.stringify(collections, null, " "));
  361.             }
  362.             {% endif %}
  363.             
  364.             /** DATALAYER: Product Page
  365.             * Fire on all Product View pages. */
  366.             
  367.             if (template.match(/.*product.*/gi) && !template.match(/.*collection.*/gi)) {
  368.                 
  369.                 sku = '';
  370.                 var product = {
  371.                     'products': [{
  372.                         'id'              : {{product.id | json}},
  373.                         'sku'             : {{product.selected_or_first_available_variant.sku | json}},
  374.                         'variantId'       : {{product.selected_or_first_available_variant.id | json}},
  375.                         'productType'     : {{product.type | json}},
  376.                         'name'            : {{product.title | json}},
  377.                         'price'           : {{product.price | money_without_currency | remove: "," | json}},
  378.                         'description'     : {{product.description | strip_newlines | strip_html | json}},
  379.                         'imageURL'        : "https:{{product.featured_image.src|img_url:'grande'}}", 
  380.                         'productURL'      : '{{shop.secure_url}}{{product.url}}',
  381.                         'brand'           : {{shop.name | json}},              
  382.                         'comparePrice'    : {{product.compare_at_price_max | money_without_currency | remove: "," | json}},
  383.                         'categories'      : {{product.collections | map:"title" | json}},
  384.                         'currentCategory' : {{collection.title | json}},
  385.                         'productOptions'  : {
  386.                             {% for option in product.options_with_values %}
  387.                             {% for value in option.values %}
  388.                             {% if option.selected_value == value %}
  389.                             {{option.name | json}} : {{value | json}},
  390.                             {% endif %}
  391.                             {% endfor %}
  392.                             {% endfor %}
  393.                         }
  394.                     }]
  395.                 };
  396.                 
  397.                 function productView(){
  398.                     var sku = {{product.selected_or_first_available_variant.sku | json}};
  399.                     dataLayer.push(product, {
  400.                         'pageType' : 'Product',
  401.                         'event'    : 'Product'});
  402.                         if(__DL__.debug){
  403.                             console.log("Product"+" :"+JSON.stringify(product, null, " "));
  404.                         }
  405.                     }
  406.                     productView();
  407.                     
  408.                     $(__DL__.cartTriggers).click(function(){
  409.                         var skumatch = {{product.selected_or_first_available_variant.sku | json}};
  410.                         if(sku != skumatch){
  411.                             productView();
  412.                         }
  413.                     });
  414.                 }
  415.                 
  416.                 /** DATALAYER: Cart View
  417.                 * Fire anytime a user views their cart (non-dynamic) */
  418.                 
  419.                 {% if template contains 'cart' %}
  420.                 var cart = {
  421.                     'products':[{% for line_item in cart.items %}{
  422.                         'id'       : {{line_item.product_id | json}},
  423.                         'sku'      : {{line_item.sku | json}},
  424.                         'variant'  : {{line_item.variant_id | json}},
  425.                         'name'     : {{line_item.title | json}},
  426.                         'price'    : {{line_item.price | money_without_currency | remove: "," | json}},
  427.                         'quantity' : {{line_item.quantity | json}}
  428.                     },{% endfor %}],
  429.                     'pageType' : 'Cart',
  430.                     'event'    : 'Cart'
  431.                 };
  432.                 
  433.                 dataLayer.push(cart);
  434.                 if(__DL__.debug){
  435.                     console.log("Cart"+" :"+JSON.stringify(cart, null, " "));
  436.                 }
  437.                 
  438.                 __DL__.cart = cart.products;
  439.                 $(__DL__.removeCartTrigger).on('click', function (event) {
  440.                     
  441.                     setTimeout(function(){
  442.                         // remove from cart
  443.                         jQuery.getJSON("/cart", function (response) {
  444.                             // get Json response 
  445.                             __DL__.removeCart = response;
  446.                             var removeFromCart = {
  447.                                 'products': __DL__.removeCart.items.map(function (line_item) {
  448.                                     return {
  449.                                         'id'       : line_item.product_id,
  450.                                         'sku'      : line_item.sku,
  451.                                         'variant'  : line_item.variant_id,
  452.                                         'name'     : line_item.title,
  453.                                         'price'    : (line_item.price/100),
  454.                                         'quantity' : line_item.quantity
  455.                                     }
  456.                                 }),
  457.                                 'pageType' : 'Remove from Cart',
  458.                                 'event'    : 'Remove from Cart'         
  459.                             };
  460.                             __DL__.removeCart = removeFromCart;
  461.                             var cartIDs = [];
  462.                             var removeIDs = [];
  463.                             var removeCart = [];
  464.                             
  465.                             // remove from cart logic
  466.                             for(var i=__DL__.cart.length-1;i>=0;i--){var x=parseFloat(__DL__.cart[i].variant);cartIDs.push(x)}for(var i=__DL__.removeCart.products.length-1;i>=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<b.length;i++){a[b[i]]=true}for(var i=0;i<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>=0;i--){if(__DL__.cart[i].variant==x){removeCart.push(__DL__.cart[i])}}
  467.                             
  468.                             dataLayer.push(removeCart);
  469.                             if (__DL__.debug) {
  470.                                 console.log("Cart"+" :"+JSON.stringify(removeCart, null, " "));
  471.                             }
  472.                         });
  473.                     }, 2000);
  474.                     
  475.                 });
  476.                 
  477.                 {% endif %}
  478.                 
  479.                 /** 
  480.                 * DATALAYER Variable
  481.                 * Checkout & Transaction Data */
  482.                 
  483.                 __DL__products = [];
  484.                 
  485.                 {% for line_item in checkout.line_items %}
  486.                 
  487.                 __DL__products.push({
  488.                     'id'          : {{line_item.product_id | json}},
  489.                     'sku'         : {{line_item.sku | json}},
  490.                     'variantId'   : {{line_item.variant_id | json}},
  491.                     'name'        : {{line_item.title | json}},
  492.                     'productType' : {{line_item.product.type | json}},
  493.                     'price'       : {{line_item.price | money_without_currency | remove: "," | json}},
  494.                     'quantity'    : {{line_item.quantity | json}},
  495.                     'description' : {{line_item.product.description | strip_newlines | strip_html  | json }},
  496.                     'imageURL'    : "https:{{line_item.product.featured_image.src|img_url:'grande'}}", 
  497.                     'productURL'  : '{{shop.secure_url}}{{line_item.product.url}}'
  498.                 });
  499.                 
  500.                 {% endfor %}
  501.                 transactionData = {
  502.                     'transactionNumber'      : {{checkout.order_id | json}},
  503.                     'transactionId'          : {{checkout.order_number | json}},
  504.                     'transactionAffiliation' : {{shop.name | json}},
  505.                     'transactionTotal'       : {{checkout.total_price | money_without_currency| remove: "," | json}},
  506.                     'transactionTax'         : {{checkout.tax_price | money_without_currency| remove: "," | json}},
  507.                     'transactionShipping'    : {{checkout.shipping_price | money_without_currency| remove: "," | json}},
  508.                     'transactionSubtotal'    : {{checkout.subtotal_price | money_without_currency| remove: "," | json}},
  509.                     {% for discount in checkout.discounts %}
  510.                     'promoCode' : {{discount.code | json}},
  511.                     'discount'  : {{discount.amoun t | money_without_currency | json}},
  512.                     {% endfor %}
  513.                     
  514.                     'products': __DL__products
  515.                 };
  516.                 
  517.                 if(__DL__.debug == true){
  518.                     
  519.                     /** DATALAYER: Transaction */
  520.                     if(document.location.pathname.match(/.*order.*/g)||document.location.pathname.match(/.*thank\_you.*/g)){
  521.                         dataLayer.push(transactionData,{
  522.                             'pageType' :'Transaction',
  523.                             'event'    :'Transaction'
  524.                         });       
  525.                         console.log("Transaction Data"+" :"+JSON.stringify(transactionData, null, " "));
  526.                     }
  527.                 }
  528.                 
  529.                 /** DATALAYER: Checkout */
  530.                 if(Shopify.Checkout){
  531.                     if(Shopify.Checkout.step){ 
  532.                         if(Shopify.Checkout.step.length > 0){
  533.                             if (Shopify.Checkout.step === 'contact_information'){
  534.                                 dataLayer.push(transactionData,{
  535.                                     'event'    :'Customer Information',
  536.                                     'pageType' :'Customer Information'});
  537.                                     console.log("Customer Information - Transaction Data"+" :"+JSON.stringify(transactionData, null, " "));
  538.                                 }else if (Shopify.Checkout.step === 'shipping_method'){
  539.                                     dataLayer.push(transactionData,{
  540.                                         'event'    :'Shipping Information',
  541.                                         'pageType' :'Shipping Information'});
  542.                                         console.log("Shipping - Transaction Data"+" :"+JSON.stringify(transactionData, null, " "));
  543.                                     }else if( Shopify.Checkout.step === "payment_method" ){
  544.                                         dataLayer.push(transactionData,{
  545.                                             'event'    :'Add Payment Info',
  546.                                             'pageType' :'Add Payment Info'});
  547.                                             console.log("Payment - Transaction Data"+" :"+JSON.stringify(transactionData, null, " "));
  548.                                         }
  549.                                     }
  550.                                     
  551.                                     if(__DL__.debug == true){
  552.                                         /** DATALAYER: Transaction */
  553.                                         if(Shopify.Checkout.page == "thank_you"){
  554.                                             dataLayer.push(transactionData,{
  555.                                                 'pageType' :'Transaction',
  556.                                                 'event'    :'Transaction'
  557.                                             });       
  558.                                             console.log("Transaction Data"+" :"+JSON.stringify(transactionData, null, " "));  
  559.                                         }
  560.                                     }else{
  561.                                         /** DATALAYER: Transaction */
  562.                                         if(Shopify.Checkout.page == "thank_you"){
  563.                                             dataLayer.push(transactionData,{
  564.                                                 'pageType' :'Transaction',
  565.                                                 'event'    :'Transaction'
  566.                                             });
  567.                                         }
  568.                                     }
  569.                                 }
  570.                             }
  571.                             
  572.                             /** DATALAYER: All Pages
  573.                             * Fire all pages trigger after all additional dataLayers have loaded. */
  574.                             
  575.                             dataLayer.push({
  576.                                 'event': 'DataLayer Loaded'
  577.                             });
  578.                             
  579.                             console.log('DATALAYER: DataLayer Loaded.');
  580.                             
  581.                             /**********************
  582.                             * DATALAYER EVENT BINDINGS
  583.                             ***********************/
  584.                             
  585.                             /** DATALAYER: 
  586.                             * Add to Cart / Dynamic Cart View
  587.                             * Fire all pages trigger after all additional dataLayers have loaded. */
  588.                             
  589.                             $(document).ready(function() {
  590.                                 
  591.                                 /** DATALAYER: Search Results */
  592.                                 
  593.                                 var searchPage = new RegExp(__DL__.searchPage, "g");
  594.                                 if(document.location.pathname.match(searchPage)){
  595.                                     var search = {
  596.                                         'searchTerm' : __DL__.searchTermQuery,
  597.                                         'pageType'   : "Search",
  598.                                         'event'      : "Search"
  599.                                     };
  600.                                     
  601.                                     dataLayer.push(search);
  602.                                     if(__DL__.debug){
  603.                                         console.log("Search"+" :"+JSON.stringify(search, null, " "));
  604.                                     }
  605.                                 }
  606.                                 
  607.                                 /** DATALAYER: Cart */
  608.                                 
  609.                                 // stage cart data
  610.                                 function mapJSONcartData(){
  611.                                     jQuery.getJSON('/cart.js', function (response) {
  612.                                         // get Json response 
  613.                                         __DL__.cart = response;
  614.                                         var cart = {
  615.                                             'products': __DL__.cart.items.map(function (line_item) {
  616.                                                 return {
  617.                                                     'id'       : line_item.id,
  618.                                                     'sku'      : line_item.sku,
  619.                                                     'variant'  : line_item.variant_id,
  620.                                                     'name'     : line_item.title,
  621.                                                     'price'    : (line_item.price/100),
  622.                                                     'quantity' : line_item.quantity
  623.                                                 }
  624.                                             }),
  625.                                             'pageType' : 'Cart',
  626.                                             'event'    : 'Cart'     
  627.                                         };
  628.                                         if(cart.products.length > 0){
  629.                                             dataLayer.push(cart);
  630.                                             if (__DL__.debug) {
  631.                                                 console.log("Cart"+" :"+JSON.stringify(cart, null, " "));
  632.                                             }
  633.                                         }
  634.                                     });
  635.                                 }
  636.                                 
  637.                                 viewcartfire = 0;
  638.                                 
  639.                                 // view cart
  640.                                 $(__DL__.viewCart).on('click', function (event) {                                    
  641.                                     if(viewcartfire !== 1){ 
  642.                                         viewcartfire = 1;
  643.                                         // if dynamic cart is TRUE
  644.                                         if (__DL__.dynamicCart) {
  645.                                             cartCheck = setInterval(function () {
  646.                                                 // begin check interval
  647.                                                 if ($(__DL__.cartVisableSelector).length > 0) {
  648.                                                     // check visible selectors
  649.                                                     clearInterval(cartCheck);
  650.                                                     mapJSONcartData();
  651.                                                     $(__DL__.removeCartTrigger).on('click', function (event) {
  652.                                                         // remove from cart
  653.                                                         var link = $(this).attr("href");
  654.                                                         jQuery.getJSON(link, function (response) {
  655.                                                             // get Json response 
  656.                                                             __DL__.removeCart = response;
  657.                                                             var removeFromCart = {
  658.                                                                 'products': __DL__.removeCart.items.map(function (line_item) {
  659.                                                                     return {
  660.                                                                         'id'       : line_item.id,
  661.                                                                         'sku'      : line_item.sku,
  662.                                                                         'variant'  : line_item.variant_id,
  663.                                                                         'name'     : line_item.title,
  664.                                                                         'price'    : (line_item.price/100),
  665.                                                                         'quantity' : line_item.quantity
  666.                                                                     }
  667.                                                                 }),
  668.                                                                 'pageType' : 'Remove from Cart',
  669.                                                                 'event'    : 'Remove from Cart'         
  670.                                                             };
  671.                                                             dataLayer.push(removeFromCart);
  672.                                                             if (__DL__.debug) {
  673.                                                                 console.log("Cart"+" :"+JSON.stringify(removeFromCart, null, " "));
  674.                                                             }
  675.                                                         });
  676.                                                     });
  677.                                                 }
  678.                                             }, 500);
  679.                                         }       
  680.                                     }
  681.                                 });
  682.                                 
  683.                                 // add to cart
  684.                                 jQuery.getJSON('/cart.js', function (response) {
  685.                                     // get Json response 
  686.                                     __DL__.cart = response;
  687.                                     var cart = {
  688.                                         'products': __DL__.cart.items.map(function (line_item) {
  689.                                             return {
  690.                                                 'id'       : line_item.id,
  691.                                                 'sku'      : line_item.sku,
  692.                                                 'variant'  : line_item.variant_id,
  693.                                                 'name'     : line_item.title,
  694.                                                 'price'    : (line_item.price/100),
  695.                                                 'quantity' : line_item.quantity
  696.                                             }
  697.                                         })
  698.                                     }
  699.                                     __DL__.cart = cart;
  700.                                     collection_cartIDs = [];
  701.                                     collection_matchIDs = [];
  702.                                     collection_addtocart = [];
  703.                                     for (var i = __DL__.cart.products.length - 1; i >= 0; i--) {
  704.                                         var x = parseFloat(__DL__.cart.products[i].variant);
  705.                                         collection_cartIDs.push(x);
  706.                                     }
  707.                                 });
  708.                                 
  709.                                 function __DL__addtocart(){
  710.  
  711.                                 {% if template contains 'collection' %}         
  712.                                     
  713.                                     setTimeout(function(){
  714.                                         jQuery.getJSON('/cart.js', function (response) {
  715.                                             // get Json response 
  716.                                             __DL__.cart = response;
  717.                                             var cart = {
  718.                                                 'products': __DL__.cart.items.map(function (line_item) {
  719.                                                     return {
  720.                                                         'id'       : line_item.id,
  721.                                                         'sku'      : line_item.sku,
  722.                                                         'variant'  : line_item.variant_id,
  723.                                                         'name'     : line_item.title,
  724.                                                         'price'    : (line_item.price/100),
  725.                                                         'quantity' : line_item.quantity
  726.                                                     }
  727.                                                 })
  728.                                             }
  729.                                             __DL__.cart = cart;
  730.                                             for (var i = __DL__.cart.products.length - 1; i >= 0; i--) {
  731.                                                 var x = parseFloat(__DL__.cart.products[i].variant);
  732.                                                 collection_matchIDs.push(x);
  733.                                             }
  734.                                             function arr_diff(b, c) {
  735.                                                 var a = [],
  736.                                                 diff = [];
  737.                                                 for (var i = 0; i < b.length; i++) {
  738.                                                     a[b[i]] = true
  739.                                                 }
  740.                                                 for (var i = 0; i < c.length; i++) {
  741.                                                     if (a[c[i]]) {
  742.                                                         delete a[c[i]]
  743.                                                     } else {
  744.                                                         a[c[i]] = true
  745.                                                     }
  746.                                                 }
  747.                                                 for (var k in a) {
  748.                                                     diff.push(k)
  749.                                                 }
  750.                                                 return diff
  751.                                             };
  752.                                             var x = arr_diff(collection_cartIDs, collection_matchIDs).pop();
  753.                                             console.log(x);
  754.                                             for (var i = __DL__.cart.products.length - 1; i >= 0; i--) {
  755.                                                 if (__DL__.cart.products[i].variant.toString() === x) {
  756.                                                     product = {'products':[__DL__.cart.products[i]]};
  757.                                                     dataLayer.push({'products':product});
  758.                                                     dataLayer.push(product);
  759.                                                     dataLayer.push({
  760.                                                         'pageType' : 'Add to Cart',
  761.                                                         'event'    : 'Add to Cart'
  762.                                                     });
  763.                                                     if (__DL__.debug) {
  764.                                                         console.log("Add to Cart"+" :"+JSON.stringify(product, null, " "));
  765.                                                     }
  766.                                                 }
  767.                                             }
  768.                                         });
  769.                                     },1000);
  770.                                     
  771.                                     {% else %}
  772.                                     
  773.                                     dataLayer.push(product, {
  774.                                         'pageType' : 'Add to Cart',
  775.                                         'event'    : 'Add to Cart'
  776.                                     });
  777.                                     
  778.                                     if (__DL__.debug) {
  779.                                         console.log("Add to Cart"+" :"+JSON.stringify(product, null, " "));
  780.                                     }
  781.                                     
  782.                                     {% endif %}
  783.                                     
  784.                                     // if dynamic cart is TRUE
  785.                                     if (__DL__.dynamicCart) {
  786.                                         console.log("dynamic");
  787.                                         var cartCheck = setInterval(function () {
  788.                                             // begin check interval
  789.                                             if ($(__DL__.cartVisableSelector).length > 0) {
  790.                                                 // check visible selectors
  791.                                                 clearInterval(cartCheck);
  792.                                                 mapJSONcartData();
  793.                                                 $(__DL__.removeCartTrigger).on('click', function (event) {
  794.                                                     // remove from cart
  795.                                                     var link = $(this).attr("href");
  796.                                                     jQuery.getJSON(link, function (response) {
  797.                                                         // get Json response 
  798.                                                         __DL__.removeCart = response;
  799.                                                         var removeFromCart = {
  800.                                                             'products': __DL__.removeCart.items.map(function (line_item) {
  801.                                                                 return {
  802.                                                                     'id'       : line_item.id,
  803.                                                                     'sku'      : line_item.sku,
  804.                                                                     'variant'  : line_item.variant_id,
  805.                                                                     'name'     : line_item.title,
  806.                                                                     'price'    : (line_item.price/100),
  807.                                                                     'quantity' : line_item.quantity
  808.                                                                 }
  809.                                                             }),
  810.                                                             'pageType' : 'Remove from Cart',
  811.                                                             'event'    : 'Remove from Cart'         
  812.                                                         };
  813.                                                         dataLayer.push(removeFromCart);
  814.                                                         if (__DL__.debug) {
  815.                                                             console.log("Cart"+" :"+JSON.stringify(removeFromCart, null, " "));
  816.                                                         }
  817.                                                     });
  818.                                                 });
  819.                                             }
  820.                                         }, 500);
  821.                                     }       
  822.                                 }
  823.                                 
  824.                                 $(document).on('click', __DL__.cartTriggers, function() {
  825.                                     __DL__addtocart();
  826.                                 });
  827.                                 
  828.                                 /** 
  829.                                  * DATALAYER: Newsletter Subscription */
  830.                                 __DL__newsletter_fire = 0;
  831.                                 $(document).on('click', __DL__.newsletterSelectors, function () {
  832.                                     if(__DL__newsletter_fire !== 1){
  833.                                         __DL__newsletter_fire = 1;
  834.                                         var newsletterCheck = setInterval(function () {
  835.                                             // begin check interval
  836.                                             if ($(__DL__.newsletterSuccess).length > 0) {
  837.                                                 // check visible selectors
  838.                                                 clearInterval(newsletterCheck);
  839.                                                 dataLayer.push({'event': 'Newsletter Subscription'});
  840.                                             }
  841.                                         },500);
  842.                                     }
  843.                                 });
  844.                                 
  845.                                 /** DATALAYER: Wishlist */
  846.                                 setTimeout( function(){
  847.                                     
  848.                                     $(__DL__.wishlistSelector).on('click', function () {
  849.                                         dataLayer.push(product,
  850.                                             {'event': 'Add to Wishlist'});
  851.                                             if(__DL__.debug){
  852.                                                 console.log("Wishlist"+" :"+JSON.stringify(product, null, " "));
  853.                                             }
  854.                                         });
  855.                                         
  856.                                         if(document.location.pathname == __DL__.wishlistPage){
  857.                                             var __DL__productLinks = $('[href*="product"]');
  858.                                             var __DL__prods        = [];
  859.                                             var __DL__links        = [];
  860.                                             var __DL__count        = 1;
  861.                                             
  862.                                             $(__DL__productLinks).each(function(){
  863.                                                 var href = $(this).attr("href");
  864.                                                 if(!__DL__links.includes(href)){
  865.                                                     __DL__links.push(href);
  866.                                                     $(this).attr("dataLayer-wishlist-item",__DL__count++);
  867.                                                     jQuery.getJSON(href, function (response) {
  868.                                                         // get Json response 
  869.                                                         __DL__.wishlist = response;
  870.                                                         var wishlistproducts = {
  871.                                                             'id'   : __DL__.wishlist.product.id,
  872.                                                             'name' : __DL__.wishlist.product.title,
  873.                                                         };
  874.                                                         __DL__prods.push(wishlistproducts);
  875.                                                     });
  876.                                                 }
  877.                                             });
  878.                                             
  879.                                             dataLayer.push({'products': __DL__prods, 
  880.                                             'pageType' : 'Wishlist',
  881.                                             'event'    : 'Wishlist'});
  882.                                         }
  883.                                         
  884.                                         var __DL__count = 1;
  885.                                         var wishlistDel  = $(__DL__.removeWishlist);
  886.                                         wishlistDel.each(function(){
  887.                                             $(this).attr("dataLayer-wishlist-item-del",__DL__count++);
  888.                                         });
  889.                                         
  890.                                         $(__DL__.removeWishlist).on('click', function(){
  891.                                             console.log('click')
  892.                                             var index = $(this).attr("dataLayer-wishlist-item-del");
  893.                                             var link  = $("[dataLayer-wishlist-item="+index+"]").attr("href");
  894.                                             console.log(index)
  895.                                             console.log(link)
  896.                                             jQuery.getJSON(link, function (response) {
  897.                                                 // get Json response 
  898.                                                 __DL__.wishlist     = response;
  899.                                                 var wishlistproducts = {
  900.                                                     'id'   : __DL__.wishlist.product.id,
  901.                                                     'name' : __DL__.wishlist.product.title,
  902.                                                 };
  903.                                                 
  904.                                                 dataLayer.push({'products': wishlistproducts,
  905.                                                 'pageType' : 'Wishlist',
  906.                                                 'event'    : 'Wishlist Delete Product'});
  907.                                             });
  908.                                         })
  909.                                     }, 3000);
  910.                                     
  911.                                     /** DATALAYER: CTAs */
  912.                                     $(__DL__.ctaSelectors).on('click', function () {
  913.                                         var ctaCheck = setInterval(function () {
  914.                                             // begin check interval
  915.                                             if ($(__DL__.ctaSuccess).length > 0) {
  916.                                                 // check visible selectors
  917.                                                 clearInterval(ctaCheck);
  918.                                                 dataLayer.push({'event': 'CTA'});
  919.                                             }
  920.                                         },500);
  921.                                     });
  922.                                     
  923.                                     /** DATALAYER: Promo Subscriptions */
  924.                                     $(__DL__.promoSubscriptionsSelectors).on('click', function () {
  925.                                         var ctaCheck = setInterval(function () {
  926.                                             // begin check interval
  927.                                             if ($(__DL__.promoSuccess).length > 0) {
  928.                                                 // check visible selectors
  929.                                                 clearInterval(ctaCheck);
  930.                                                 dataLayer.push({'event': 'Promo Subscription'});
  931.                                             }
  932.                                         },500);
  933.                                     });
  934.                                     
  935.                                 }); // document ready
  936.                             }
  937.                         }, 500);
  938.                         </script>

Editor

You can edit this paste and save as new:


File Description
  • code
  • Paste Code
  • 05 Jun-2023
  • 53.15 Kb
You can Share it: