This repository has been archived by the owner on Aug 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 472
/
ajaxify.js.liquid
1147 lines (968 loc) · 32.5 KB
/
ajaxify.js.liquid
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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*============================================================================
(c) Copyright 2014 Shopify Inc. Author: Carson Shold (@cshold). All Rights Reserved.
Plugin Documentation - http://shopify.github.io/Timber/#ajax-cart
Ajaxify the add to cart experience and flip the button for inline confirmation,
show the cart in a modal, or a 3D drawer.
This file includes:
- Basic Shopify Ajax API calls
- Ajaxify cart plugin
This requires:
- jQuery 1.8+
- handlebars.min.js (for cart template)
- modernizer.min.js
- snippet/ajax-cart-template.liquid
JQUERY API (c) Copyright 2009-2014 Shopify Inc. Author: Caroline Schnapp. All Rights Reserved.
Includes slight modifications to addItemFromForm.
==============================================================================*/
if ((typeof Shopify) === 'undefined') { Shopify = {}; }
/*============================================================================
Basic JS Helper Functions
==============================================================================*/
function urlParams (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
/*============================================================================
API Helper Functions
==============================================================================*/
function attributeToString(attribute) {
if ((typeof attribute) !== 'string') {
attribute += '';
if (attribute === 'undefined') {
attribute = '';
}
}
return jQuery.trim(attribute);
};
/*============================================================================
API Functions
- Shopify.format money is defined in option_selection.js.
If that file is not included, it is redefined here.
==============================================================================*/
if (!Shopify.formatMoney) {
Shopify.formatMoney = function(cents, format) {
var value = '',
placeholderRegex = /\{\{\s*(\w+)\s*\}\}/,
formatString = (format || this.money_format);
if (typeof cents == 'string') {
cents = cents.replace('.','');
}
function defaultOption(opt, def) {
return (typeof opt == 'undefined' ? def : opt);
}
function formatWithDelimiters(number, precision, thousands, decimal) {
precision = defaultOption(precision, 2);
thousands = defaultOption(thousands, ',');
decimal = defaultOption(decimal, '.');
if (isNaN(number) || number == null) {
return 0;
}
number = (number/100.0).toFixed(precision);
var parts = number.split('.'),
dollars = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands),
cents = parts[1] ? (decimal + parts[1]) : '';
return dollars + cents;
}
switch(formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(cents, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(cents, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(cents, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(cents, 0, '.', ',');
break;
}
return formatString.replace(placeholderRegex, value);
};
}
Shopify.onProduct = function(product) {
// alert('Received everything we ever wanted to know about ' + product.title);
};
Shopify.onCartUpdate = function(cart) {
// alert('There are now ' + cart.item_count + ' items in the cart.');
};
Shopify.updateCartNote = function(note, callback) {
var params = {
type: 'POST',
url: '/cart/update.js',
data: 'note=' + attributeToString(note),
dataType: 'json',
success: function(cart) {
if ((typeof callback) === 'function') {
callback(cart);
}
else {
Shopify.onCartUpdate(cart);
}
},
error: function(XMLHttpRequest, textStatus) {
Shopify.onError(XMLHttpRequest, textStatus);
}
};
jQuery.ajax(params);
};
Shopify.onError = function(XMLHttpRequest, textStatus) {
var data = eval('(' + XMLHttpRequest.responseText + ')');
if (!!data.message) {
alert(data.message + '(' + data.status + '): ' + data.description);
} else {
alert('Error : ' + Shopify.fullMessagesFromErrors(data).join('; ') + '.');
}
};
/*============================================================================
POST to cart/add.js returns the JSON of the line item associated with the added item
==============================================================================*/
Shopify.addItem = function(variant_id, quantity, callback) {
var quantity = quantity || 1,
params = {
type: 'POST',
url: '/cart/add.js',
data: 'quantity=' + quantity + '&id=' + variant_id,
dataType: 'json',
success: function(line_item) {
if ((typeof callback) === 'function') {
callback(line_item);
}
else {
Shopify.onItemAdded(line_item);
}
},
error: function(XMLHttpRequest, textStatus) {
Shopify.onError(XMLHttpRequest, textStatus);
}
};
jQuery.ajax(params);
};
/*============================================================================
POST to cart/add.js returns the JSON of the line item
- Allow use of form element instead of id
- Allow custom error callback
==============================================================================*/
Shopify.addItemFromForm = function(form, callback, errorCallback) {
var params = {
type: 'POST',
url: '/cart/add.js',
data: jQuery(form).serialize(),
dataType: 'json',
success: function(line_item) {
if ((typeof callback) === 'function') {
callback(line_item, form);
}
else {
Shopify.onItemAdded(line_item, form);
}
},
error: function(XMLHttpRequest, textStatus) {
if ((typeof errorCallback) === 'function') {
errorCallback(XMLHttpRequest, textStatus);
}
else {
Shopify.onError(XMLHttpRequest, textStatus);
}
}
};
jQuery.ajax(params);
};
// Get from cart.js returns the cart in JSON
Shopify.getCart = function(callback) {
jQuery.getJSON('/cart.js', function (cart, textStatus) {
if ((typeof callback) === 'function') {
callback(cart);
}
else {
Shopify.onCartUpdate(cart);
}
});
};
// GET products/<product-handle>.js returns the product in JSON
Shopify.getProduct = function(handle, callback) {
jQuery.getJSON('/products/' + handle + '.js', function (product, textStatus) {
if ((typeof callback) === 'function') {
callback(product);
}
else {
Shopify.onProduct(product);
}
});
};
// POST to cart/change.js returns the cart in JSON
Shopify.changeItem = function(variant_id, quantity, callback) {
var params = {
type: 'POST',
url: '/cart/change.js',
data: 'quantity='+quantity+'&id='+variant_id,
dataType: 'json',
success: function(cart) {
if ((typeof callback) === 'function') {
callback(cart);
}
else {
Shopify.onCartUpdate(cart);
}
},
error: function(XMLHttpRequest, textStatus) {
Shopify.onError(XMLHttpRequest, textStatus);
}
};
jQuery.ajax(params);
};
/*============================================================================
Ajaxify Shopify Add To Cart
==============================================================================*/
var ajaxifyShopify = (function(module, $) {
'use strict';
// Public functions
var init;
// Private general variables
var settings, cartInit, $drawerHeight, $cssTransforms, $cssTransforms3d, $nojQueryLoad, $w, $body, $html;
// Private plugin variables
var $formContainer, $btnClass, $wrapperClass, $addToCart, $flipClose, $flipCart, $flipContainer, $cartCountSelector, $cartCostSelector, $toggleCartButton, $modal, $cartContainer, $drawerCaret, $modalContainer, $modalOverlay, $closeCart, $drawerContainer, $prependDrawerTo, $callbackData={};
// Private functions
var updateCountPrice, flipSetup, revertFlipButton, modalSetup, showModal, sizeModal, hideModal, drawerSetup, showDrawer, hideDrawer, sizeDrawer, loadCartImages, formOverride, itemAddedCallback, itemErrorCallback, cartUpdateCallback, setToggleButtons, flipCartUpdateCallback, buildCart, cartTemplate, adjustCart, adjustCartCallback, createQtySelectors, qtySelectors, validateQty, scrollTop, toggleCallback;
/*============================================================================
Initialise the plugin and define global options
==============================================================================*/
init = function (options) {
// Default settings
settings = {
method: 'drawer', // Method options are drawer, modal, and flip. Default is drawer.
formSelector: 'form[action^="/cart/add"]',
addToCartSelector: 'input[type="submit"]',
cartCountSelector: null,
cartCostSelector: null,
toggleCartButton: null,
btnClass: null,
wrapperClass: null,
useCartTemplate: true,
moneyFormat: '${{amount}}',
disableAjaxCart: false,
enableQtySelectors: true,
prependDrawerTo: 'body',
onToggleCallback: null
};
// Override defaults with arguments
$.extend(settings, options);
// If method parameter is set, override the defined method (used for demos)
if (urlParams('method')) {
settings.method = urlParams('method');
}
// Make sure method is lower case
settings.method = settings.method.toLowerCase();
// Select DOM elements
$formContainer = $(settings.formSelector);
$btnClass = settings.btnClass;
$wrapperClass = settings.wrapperClass;
$addToCart = $formContainer.find(settings.addToCartSelector);
$flipContainer = null;
$flipClose = null;
$cartCountSelector = $(settings.cartCountSelector);
$cartCostSelector = $(settings.cartCostSelector);
$toggleCartButton = $(settings.toggleCartButton);
$modal = null;
$prependDrawerTo = $(settings.prependDrawerTo);
// CSS Checks
$cssTransforms = Modernizr.csstransforms;
$cssTransforms3d = Modernizr.csstransforms3d;
// General Selectors
$w = $(window);
$body = $('body');
$html = $('html');
// Check if we can use .load
$nojQueryLoad = $html.hasClass('lt-ie9');
if ($nojQueryLoad) {
settings.useCartTemplate = false;
}
// Setup ajax quantity selectors on the any template if enableQtySelectors is true
if (settings.enableQtySelectors) {
qtySelectors();
}
// Enable the ajax cart
if (!settings.disableAjaxCart) {
// Handle each case add to cart method
switch (settings.method) {
case 'flip':
flipSetup();
break;
case 'modal':
modalSetup();
break;
case 'drawer':
drawerSetup();
break;
}
// Escape key closes cart
$(document).keyup(function (evt) {
if (evt.keyCode == 27) {
switch (settings.method) {
case 'flip':
case 'drawer':
hideDrawer();
break;
case 'modal':
hideModal();
break;
}
}
});
if ($addToCart.length) {
// Take over the add to cart form submit
formOverride();
}
}
// Run this function in case we're using the quantity selector outside of the cart
adjustCart();
};
updateCountPrice = function (cart) {
if ($cartCountSelector) {
$cartCountSelector.html(cart.item_count).removeClass('hidden-count');
if (cart.item_count === 0) {
$cartCountSelector.addClass('hidden-count');
}
}
if ($cartCostSelector) {
$cartCostSelector.html(Shopify.formatMoney(cart.total_price, settings.moneyFormat));
}
};
flipSetup = function () {
// Build and append the drawer in the DOM
drawerSetup();
// Stop if there is no add to cart button
if (!$addToCart.length) {
return
}
// Wrap the add to cart button in a div
$addToCart.addClass('flip__front').wrap('<div class="flip"></div>');
// Write a (hidden) Checkout button, a loader, and the extra view cart button
var checkoutBtn = $('<a href="/cart" class="flip__back" style="background-color: #C00; color: #fff;" class="flip__checkout">{{ 'cart.general.checkout' | t | json }} </a>').addClass($btnClass),
flipLoader = $('<span class="ajaxcart__flip-loader"></span>'),
flipExtra = $('<div class="flip__extra"><a href="#" class="flip__cart">{{ 'cart.general.view_cart' | t | json }} (<span></span>)</a></div>');
// Append checkout button and loader
checkoutBtn.insertAfter($addToCart);
flipLoader.insertAfter(checkoutBtn);
// Setup new selectors
$flipContainer = $('.flip');
if (!$cssTransforms3d) {
$flipContainer.addClass('no-transforms')
}
// Setup extra selectors once appended
flipExtra.insertAfter($flipContainer);
$flipCart = $('.flip__cart');
$flipCart.on('click', function(e) {
e.preventDefault();
showDrawer(true);
});
// Reset the button if a user changes a variation
$('input[type="checkbox"], input[type="radio"], select', $formContainer).on('click', function() {
revertFlipButton();
})
};
revertFlipButton = function () {
$flipContainer.removeClass('is-flipped');
};
modalSetup = function () {
// Create modal DOM elements with handlebars.js template
var source = $("#ModalTemplate").html(),
template = Handlebars.compile(source);
// Append modal and overlay to body
$body.append(template).append('<div class="ajaxcart__overlay"></div>');
// Modal selectors
$modalContainer = $('#AjaxifyModal');
$modalOverlay = $('.ajaxcart__overlay');
$cartContainer = $('#AjaxifyCart');
// Close modal when clicking the overlay
$modalOverlay.on('click', hideModal);
// Create a close modal button
$modalContainer.prepend('<button type="button" class="ajaxcart__close" title="' + {{ 'cart.general.close_cart' | t | json }} + '">' + {{ 'cart.general.close_cart' | t | json }} + '</button>');
$closeCart = $('.ajaxcart__close');
$closeCart.on('click', hideModal);
// Add a class if CSS translate isn't available
if (!$cssTransforms) {
$modalContainer.addClass('no-transforms')
}
// Update modal position on screen changes
$(window).on({
orientationchange: function(e) {
if ($modalContainer.hasClass('is-visible')) {
sizeModal('resize');
}
}, resize: function(e) {
// IE8 fires this when overflow on body is changed. Ignore IE8.
if (!$nojQueryLoad && $modalContainer.hasClass('is-visible')) {
sizeModal('resize');
}
}
});
// Toggle modal with cart button
setToggleButtons();
};
showModal = function (toggle) {
$body.addClass('ajaxcart--is-visible');
// Build the cart if it isn't already there
if (!cartInit && toggle) {
Shopify.getCart(cartUpdateCallback);
} else {
sizeModal();
}
};
sizeModal = function(isResizing) {
if (!isResizing) {
$modalContainer.css('opacity', 0);
}
// Position modal by negative margin
$modalContainer.css({
'margin-left': - ($modalContainer.outerWidth() / 2),
'opacity': 1
});
// Position close button relative to title
$closeCart.css({
'top': 10 + ($cartContainer.find('h1').height() / 2)
})
$modalContainer.addClass('is-visible');
scrollTop();
toggleCallback({
'is_visible': true
});
};
hideModal = function (e) {
$body.removeClass('ajaxcart--is-visible');
if (e) {
e.preventDefault();
}
if ($modalContainer) {
$modalContainer.removeClass('is-visible');
$body.removeClass('ajaxify-lock');
}
toggleCallback({
'is_visible': false
});
};
drawerSetup = function () {
// Create drawer DOM elements with handlebars.js template
var source = $("#DrawerTemplate").html(),
template = Handlebars.compile(source),
data = {
wrapperClass: $wrapperClass
};
// Append drawer (defaults to body)
$prependDrawerTo.prepend(template(data));
// Drawer selectors
$drawerContainer = $('#AjaxifyDrawer');
$cartContainer = $('#AjaxifyCart');
$drawerCaret = $('.ajaxcart__caret > span');
// Toggle drawer with cart button
setToggleButtons();
// Position caret and size drawer on resize if drawer is visible
var timeout;
$(window).resize(function() {
clearTimeout(timeout);
timeout = setTimeout(function(){
if ($drawerContainer.hasClass('is-visible')) {
positionCaret();
sizeDrawer();
}
}, 500);
});
// Position the caret the first time
positionCaret();
// Position the caret
function positionCaret() {
if ($toggleCartButton.offset()) {
// Get the position of the toggle button to align the caret with
var togglePos = $toggleCartButton.offset(),
toggleWidth = $toggleCartButton.outerWidth(),
toggleMiddle = togglePos.left + toggleWidth/2;
$drawerCaret.css('left', toggleMiddle + 'px');
}
}
};
showDrawer = function (toggle) {
// If we're toggling with the flip method, use a special callback
if (settings.method == 'flip') {
Shopify.getCart(flipCartUpdateCallback);
}
// opening the drawer for the first time
else if (!cartInit && toggle) {
Shopify.getCart(cartUpdateCallback);
}
// simple toggle? just size it
else if (cartInit && toggle) {
sizeDrawer();
}
// Show the drawer
$drawerContainer.addClass('is-visible');
scrollTop();
toggleCallback({
'is_visible': true
});
};
hideDrawer = function () {
$drawerContainer.removeAttr('style').removeClass('is-visible');
scrollTop();
toggleCallback({
'is_visible': false
});
};
sizeDrawer = function ($empty) {
if ($empty) {
$drawerContainer.css('height', '0px');
} else {
$drawerHeight = $cartContainer.outerHeight();
$('.cart__row img').css('width', 'auto'); // fix Chrome image size bug
$drawerContainer.css('height', $drawerHeight + 'px');
}
};
loadCartImages = function () {
// Size cart once all images are loaded
var cartImages = $('img', $cartContainer),
count = cartImages.length,
index = 0;
cartImages.on('load', function() {
index++;
if (index==count) {
switch (settings.method) {
case 'modal':
sizeModal();
break;
case 'flip':
case 'drawer':
sizeDrawer();
break;
}
}
});
};
formOverride = function () {
$formContainer.submit(function(e) {
e.preventDefault();
// Add class to be styled if desired
$addToCart.removeClass('is-added').addClass('is-adding');
// Remove any previous quantity errors
$('.qty-error').remove();
Shopify.addItemFromForm(e.target, itemAddedCallback, itemErrorCallback);
// Set the flip button to a loading state
switch (settings.method) {
case 'flip':
$flipContainer.addClass('flip--is-loading');
break;
}
});
};
itemAddedCallback = function (product) {
$addToCart.removeClass('is-adding').addClass('is-added');
// Slight delay of flip to mimic a longer load
switch (settings.method) {
case 'flip':
setTimeout(function () {
$flipContainer.removeClass('flip--is-loading').addClass('is-flipped');
}, 600);
break;
}
Shopify.getCart(cartUpdateCallback);
};
itemErrorCallback = function (XMLHttpRequest, textStatus) {
var data = eval('(' + XMLHttpRequest.responseText + ')');
switch (settings.method) {
case 'flip':
$flipContainer.removeClass('flip--is-loading');
break;
}
if (!!data.message) {
if (data.status == 422) {
$formContainer.after('<div class="errors qty-error">'+ data.description +'</div>')
}
}
};
cartUpdateCallback = function (cart) {
// Update quantity and price
updateCountPrice(cart);
switch (settings.method) {
case 'flip':
$('.flip__cart span').html(cart.item_count);
break;
case 'modal':
buildCart(cart);
break;
case 'drawer':
buildCart(cart);
if (!$drawerContainer.hasClass('is-visible')) {
showDrawer();
} else {
scrollTop();
}
break;
}
};
setToggleButtons = function () {
// Reselect the element in case it just loaded
$toggleCartButton = $(settings.toggleCartButton);
if ($toggleCartButton) {
// Turn it off by default, in case it's initialized twice
$toggleCartButton.off('click');
// Toggle the cart, based on the method
$toggleCartButton.on('click', function(e) {
e.preventDefault();
switch (settings.method) {
case 'modal':
if ($modalContainer.hasClass('is-visible')) {
hideModal();
} else {
showModal(true);
}
break;
case 'drawer':
case 'flip':
if ($drawerContainer.hasClass('is-visible')) {
hideDrawer();
} else {
showDrawer(true);
}
break;
}
});
}
};
flipCartUpdateCallback = function (cart) {
buildCart(cart);
};
buildCart = function (cart) {
// Empty cart if using default layout or not using the .load method to get /cart
if (!settings.useCartTemplate || cart.item_count === 0) {
$cartContainer.empty();
}
// Show empty cart
if (cart.item_count === 0) {
$cartContainer
.append('<h2>' + {{ 'cart.general.empty' | t | json }} + '</h2>')
.append('<p>' + {{ 'cart.general.continue_browsing_html' | t | json }} + '</p>');
switch (settings.method) {
case 'modal':
sizeModal('resize');
break;
case 'flip':
case 'drawer':
sizeDrawer();
if (!$drawerContainer.hasClass('is-visible') && cartInit) {
sizeDrawer(true);
}
break;
}
return;
}
// Use the /cart template, or Handlebars.js layout based on theme settings
if (settings.useCartTemplate) {
cartTemplate(cart);
return;
}
// Handlebars.js cart layout
var items = [],
item = {},
data = {},
source = $("#CartTemplate").html(),
template = Handlebars.compile(source);
// Add each item to our handlebars.js data
$.each(cart.items, function(index, cartItem) {
var itemAdd = cartItem.quantity + 1,
itemMinus = cartItem.quantity - 1,
itemQty = cartItem.quantity;
/* Hack to get product image thumbnail
* - If image is not null
* - Remove file extension, add _small, and re-add extension
* - Create server relative link
* - A hard-coded url of no-image
*/
if (cartItem.image != null){
var prodImg = cartItem.image.replace(/(\.[^.]*)$/, "_small$1").replace('http:', '');
} else {
var prodImg = "http://cdn.shopify.com/s/assets/admin/no-image-medium-cc9732cb976dd349a0df1d39816fbcc7.gif";
}
var prodName = cartItem.title.replace(/(\-[^-]*)$/, ""),
prodVariation = cartItem.title.replace(/^[^\-]*/, "").replace(/-/, "");
// Create item's data object and add to 'items' array
item = {
id: cartItem.variant_id,
url: cartItem.url,
img: prodImg,
name: prodName,
variation: prodVariation,
itemAdd: itemAdd,
itemMinus: itemMinus,
itemQty: itemQty,
price: Shopify.formatMoney(cartItem.price, settings.moneyFormat)
};
items.push(item);
});
// Gather all cart data and add to DOM
data = {
items: items,
totalPrice: Shopify.formatMoney(cart.total_price, settings.moneyFormat),
btnClass: $btnClass
}
$cartContainer.append(template(data));
// With new elements we need to relink the adjust cart functions
adjustCart();
// Setup close modal button and size drawer
switch (settings.method) {
case 'modal':
loadCartImages();
break;
case 'flip':
case 'drawer':
if (cart.item_count > 0) {
loadCartImages();
} else {
sizeDrawer(true);
}
break;
default:
break;
}
// Mark the cart as built
cartInit = true;
};
cartTemplate = function (cart) {
var url = '/cart?' + Date.now() + ' form[action="/cart"]';
$cartContainer.load(url, function() {
// With new elements we need to relink the adjust cart functions
adjustCart();
// Size drawer at this point
switch (settings.method) {
case 'modal':
loadCartImages();
break;
case 'flip':
case 'drawer':
if (cart.item_count > 0) {
loadCartImages();
} else {
sizeDrawer(true);
}
// Create a close drawer button
$cartContainer.prepend('<button type="button" class="ajaxcart__close" title="' + {{ 'cart.general.close_cart' | t | json }} + '">' + {{ 'cart.general.close_cart' | t | json }} + '</button>');
$closeCart = $('.ajaxcart__close');
$closeCart.on('click', hideDrawer);
break;
default:
break;
}
// Mark the cart as built
cartInit = true;
});
}
adjustCart = function () {
// This function runs on load, and when the cart is reprinted
// Create ajax friendly quantity fields and remove links in the ajax cart
if (settings.useCartTemplate) {
createQtySelectors();
}
// Update quantify selectors
var qtyAdjust = $('.ajaxcart__qty-adjust');
// Add or remove from the quantity
qtyAdjust.off('click');
qtyAdjust.on('click', function() {
var el = $(this),
id = el.data('id'),
qtySelector = el.siblings('.ajaxcart__qty-num'),
qty = parseInt(qtySelector.val().replace(/\D/g, ''));
var qty = validateQty(qty);
// Add or subtract from the current quantity
if (el.hasClass('ajaxcart__qty--plus')) {
qty = qty + 1;
} else {
qty = qty - 1;
if (qty <= 0) qty = 0;
}
// If it has a data-id, update the cart.
// Otherwise, just update the input's number
if (id) {
updateQuantity(id, qty);
} else {
qtySelector.val(qty);
}
});
// Update quantity based on input on change
var qtyInput = $('.ajaxcart__qty-num');
qtyInput.off('change');
qtyInput.on('change', function() {
var el = $(this),
id = el.data('id'),
qty = parseInt(el.val().replace(/\D/g, ''));
var qty = validateQty(qty);
// Only update the cart via ajax if we have a variant ID to work with
if (id) {
updateQuantity(id, qty);
}
});
// Highlight the text when focused
qtyInput.off('focus');
qtyInput.on('focus', function() {
var el = $(this);
setTimeout(function() {
el.select();
}, 50);
});
// Completely remove product
$('.ajaxcart__remove').on('click', function(e) {
var el = $(this),
id = el.data('id') || null,
qty = 0;
// Without an id, let the default link action take over
if (!id) {
return;
}
e.preventDefault();
updateQuantity(id, qty);
});
function updateQuantity(id, qty) {
// Add activity classes when changing cart quantities
if (!settings.useCartTemplate) {
var row = $('.ajaxcart__row[data-id="' + id + '"]').addClass('is-loading');
} else {
var row = $('.cart__row[data-id="' + id + '"]').addClass('is-loading');
}
if (qty === 0) {
row.addClass('is-removed');
}
// Slight delay to make sure removed animation is done
setTimeout(function() {
Shopify.changeItem(id, qty, adjustCartCallback);
}, 250);
}
// Save note anytime it's changed
var noteArea = $('textarea[name="note"]');
noteArea.off('change');
noteArea.on('change', function() {
var newNote = $(this).val();
// Simply updating the cart note in case they don't click update/checkout
Shopify.updateCartNote(newNote, function(cart) {});
});
};