-
Notifications
You must be signed in to change notification settings - Fork 7
/
jquery.shopify-ajax-cart.js
89 lines (79 loc) · 2.96 KB
/
jquery.shopify-ajax-cart.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
/*
* Project: Shopify AJAX Cart Plugin
* Description: Provides AJAX cart functionality for interacting with the Shopify AJAX API so you don't need an "Update Cart" button
* Dependency: jQuery 1.6+
* Author: Ryan Marshall ([email protected])
* License: Free
* Usage:
*
* $('#cart-form').shopifyAJAXCart({
* item: '.line-item-container',
* item_total: '.line-item-total',
* item_qty: '.line-item-qty',
* subtotal: '.cart-total-price'
* });
*
*/
;(function ( $, window, document, undefined ) {
var pluginName = 'shopifyAJAXCart',
defaults = {
propertyName: "value"
};
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = 'shopifyAJAXCart';
this.init();
}
Plugin.prototype = {
init: function() {
var item = this.options.item,
item_total = this.options.item_total,
item_qty = this.options.item_qty,
subtotal = $(this.options.subtotal);
// Change line item quantity
$(item_qty).change(function() {
var qty = $(this).val(),
this_item = $(this).closest(item),
variant_id = this_item.data('variant-id'),
this_item_total = this_item.find(item_total);
$.ajax({
type: 'POST',
url: '/cart/change.js',
dataType: 'json',
data: {
quantity: qty,
id: variant_id
},
success: function(cart) {
if ( qty == 0 ) {
this_item.remove();
} else {
$.each(cart.items,function(index,row) {
if ( variant_id == row.variant_id ) this_item_total.html( '$' + parseFloat(row.line_price / 100).toFixed(2) );
});
}
subtotal.html( '$' + parseFloat(cart.total_price / 100).toFixed(2) );
},
error: function(response) {
alert(response);
}
});
});
// Remove line item
$(this.options.item_remove).click(function(e) {
e.preventDefault();
$(this).closest(item).find(item_qty).val(0);
$(this).closest(item).find(item_qty).trigger('change');
});
}
};
$.fn.shopifyAJAXCart = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );