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