Options
Configuration options are passed to CartJS.init()
when initialising Cart.js.
See the Configuration section in the Guide for more.
dataAPI
Boolean (default: true
)
When true
, Cart.js will automatically bind document
listeners for events related to element you've marked up with data-cart-
attributes.
If you're not making use of the Data API and are super-concerned with performance, you can set this to false
, but in reality you'll probably never need to adjust this.
debug
Boolean (default: false
)
When true
, debugging and error messages will be printed to the console as Cart.js initialises and makes requests.
requestBodyClass
String (default: null
)
If provided, Cart.js will automatically apply this class to the body
element while an Ajax request is ongoing.
Useful for displaying a loading animation while an Ajax request is waiting to complete - for example:
<style>
.show-when-loading {
display: none;
}
body.loading .show-when-loading {
display: inline-block;
}
</style>
<body>
<button data-cart-add="12345678">Add a Product</button>
<img src="{{ 'loader.gif' | asset_url }}" class="" width="16" height="16" alt="Loading..." />
</body>
moneyFormat
String (default: null
)
Specifies the formatting to be used when rendering money amounts through elements marked up with data-cart-render
or via the DOM Bindings.
You can use Liquid to render the appropriate format from the shop's settings, for example:
<script type="text/javascript">
$(function() {
CartJS.init({{ cart | json }}, {
"moneyFormat": "{{ shop.money_format }}",
"moneyWithCurrencyFormat": "{{ shop.money_with_currency_format }}"
});
});
</script>
When using money formatting options, don't forget to include Shopify's option_selection.js
on all pages.
See the note "Dependency when formatting monetary values" in the Guide for more detail.
moneyWithCurrencyFormat
String (default: null
)
Specifies the formatting to be used when rendering money amounts with currencies through elements marked up with data-cart-render
or via the DOM Bindings.
You can use Liquid to render the appropriate format from the shop's settings, for example:
<script type="text/javascript">
$(function() {
CartJS.init({{ cart | json }}, {
"moneyFormat": "{{ shop.money_format }}",
"moneyWithCurrencyFormat": "{{ shop.money_with_currency_format }}"
});
});
</script>
When using money formatting options, don't forget to include Shopify's option_selection.js
on all pages.
See the note "Dependency when formatting monetary values" in the Guide for more detail.
weightUnit
String (default: 'g'
)
Specifies the weight unit to use when rendering weights through the provided
weight
or weightWithUnit
formatters. Possible values are g
, kg
, oz
or
lb
.
weightPrecision
Integer (default: 0
)
Specifies the number of decimal places to display when formatting weights with
the provided weight
or weightWithUnit
formatters. Defaults to 0
to match
the default weight unit, which is grams.
rivetsModels
Object (default: {}
)
If you're using Rivets.js for DOM bindings, this setting allows you to pass additional data models that can be used in your rendered views.
<div data-cart-view>
Your name is {customer.name}.
</div>
<script type="text/javascript">
$(function() {
CartJS.init({{ cart | json }}, {
rivetsModels: {
"customer": {{ customer | json }}
}
});
});
</script>
Core API
Core API methods are available on the global CartJS
object.
They can be called from anywhere - an event handler, your startup code, even in an onclick=""
attribute if you're feeling old school.
See the Core API section in the Guide for more.
addItem
CartJS.addItem(id, quantity = 1, properties = {}, options = {})
Add the variant with the given id
to the cart, optionally specifying a quantity
(default 1
) and a hash of custom line item properties
.
// Add five items with the variant id 12345678 to the cart, with a custom size property.
CartJS.addItem(12345678, 5, {
"size": "XL"
});
The final optional options
hash allows you to specify callback functions to trigger after the item has been added.
Available callbacks mirror those provided by jQuery's $.ajax()
callbacks (success
, error
and complete
), and are passed the same arguments.
// Do the same as above, but handle the result of the call with either a success or error message.
CartJS.addItem(12345678, 5, {
"size": "XL"
}, {
"success": function(data, textStatus, jqXHR) {
alert('Added!');
},
"error": function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + errorThrown + '!');
}
});
As with jQuery callbacks, you can optionally provide an array of callback functions to execute.
updateItem
CartJS.updateItem(line_number, quantity, properties = {}, options = {})
Update the quantity and properties of the line item with the specified line_number
in the cart.
Line numbers are one-indexed; that is, the first line item has a line_number
of 1
.
Setting quantity
to 0
will remove the item from the cart.
Leaving quantity
as undefined
will leave the quantity of the item as-is.
// Let's have 6 of the first item in the cart.
CartJS.updateItem(1, 6);
See addItem for details on the options
hash.
removeItem
CartJS.removeItem(line_number, options = {})
Remove the line item with the specified line_number
from the cart.
Line numbers are one-indexed; that is, the first line item has a line_number
of 1
.
// Remove the first line item from the cart.
CartJS.removeItem(1);
See addItem for details on the options
hash.
updateItemById
CartJS.updateItemById(id, quantity, properties = {}, options = {})
Update the quantity and properties of the line item with the specified variant id
in the cart.
If multiple line items exist for the specified variant, all of them will be updated.
Setting quantity
to 0
will remove all items with the specified variant id
from the cart.
Leaving quantity
as undefined
will leave the quantity of the items as-is.
// Make sure we have six pairs of blue socks (variant #12345678).
CartJS.updateItemById(12345678, 6);
See addItem for details on the options
hash.
updateItemQuantitiesById
CartJS.updateItemQuantitiesById(updates = {}, options = {})
Update the quantities of many line items in the cart at once, using a mapping of variant IDs
to the desired quantity. Line items with variants IDs omitted from the updates
hash will
not have their quantities changed.
// Make sure we have 6x blue socks (variant #12345678) and 0x red socks (variant #12345680).
CartJS.updateItemQuantitiesById({12345678: 6, 12345680: 0});
See addItem for details on the options
hash.
removeItemById
CartJS.removeItemById(id, options = {})
Remove the line item with the specified variant id
from the cart.
If multiple line items exist for the specified variant, all of them will be removed.
// Get rid of all blue socks (variant #12345678) from our order.
CartJS.removeItemById(12345678);
See addItem for details on the options
hash.
clear
CartJS.clear(options = {})
Clear the cart of all line items. Does not clear cart attributes or the cart note.
// Clear all items from the cart.
CartJS.clear();
See addItem for details on the options
hash.
getAttribute
CartJS.getAttribute(attributeName, defaultValue = undefined)
Get the cart attribute specified by attributeName
.
If the specified attribute isn't set, defaultValue
will be returned (defaults to undefined
).
// See if the cart has a gift note (by default it doesn't).
var hasGiftNote = CartJS.getAttribute('Has Gift Note', false);
if(hasGiftNote) {
var giftMessage = prompt('Please enter your gift note:');
}
setAttribute
CartJS.setAttribute(attributeName, value, options = {})
Set the attribute specified by attributeName
to the specified value
.
// If there's a giftable item in our order, flag that we need a gift note.
if(hasGiftableItem) {
CartJS.setAttribute('Has Gift Note', true);
}
See addItem for details on the options
hash.
getAttributes
CartJS.getAttributes()
Get all currently set cart attributes, returned as an object.
// Print out current cart attributes.
console.log(CartJS.getAttributes());
// -> Object {"Has Gift Note": "false"}
setAttributes
CartJS.setAttributes(attributes = {}, options = {})
Set multiple cart attributes at once by passing an attributes
hash.
// Flag that the cart has a gift note, and set the content of that note.
CartJS.setAttributes({
"Has Gift Note": true,
"Gift Note": "Happy Birthday!"
});
See addItem for details on the options
hash.
clearAttributes
CartJS.clearAttributes(options = {})
Clear all cart attributes. Does not clear cart line items or the cart note.
// Clear all attributes from the cart.
CartJS.clearAttributes();
See addItem for details on the options
hash.
getNote
CartJS.getNote()
Returns the current cart note.
// Let the customer know what the current cart note is.
alert('Your cart note is currently: ' + CartJS.getNote());
setNote
CartJS.setNote(note, options = {})
Set the cart note.
// Get any notes from the customer.
CartJS.setNote(prompt("Please add any notes: "));
See addItem for details on the options
hash.
Data API
Data API markup should be added to your HTML to hook in to Cart.js without the need to write Javascript.
See the Data API section in the Guide for more.
data-cart-add
<button data-cart-add="12345678" data-cart-quantity="1">Add to Cart</button>
On a click
event, add the variant given by data-cart-add
to the cart.
You can specify a quantity to add with an optional data-cart-quantity
attribute.
data-cart-remove
<button data-cart-remove="1">Remove from Cart</button>
On a click
event, remove the line number given by data-cart-remove
from the cart.
Line numbers are one-indexed; that is, the first line item has a line number of 1
.
data-cart-remove-id
<button data-cart-remove-id="12345678">Remove from Cart</button>
On a click
event, remove the variant given by data-cart-remove-id
from the cart.
If multiple line items exist for the specified variant, all of them will be removed.
data-cart-update
<button data-cart-update="1" data-cart-quantity="5">Change to 5</button>
On a click
event, update the line number given by data-cart-update
in the cart.
You can use the data-cart-quantity
attribute to specify the new quantity.
Line numbers are one-indexed; that is, the first line item has a line number of 1
.
data-cart-update-id
<button data-cart-update-id="12345678" data-cart-quantity="5">Change to 5</button>
On a click
event, update the variant given by data-cart-update-id
in the cart.
You can use the data-cart-quantity
attribute to specify the new quantity.
If multiple line items exist for the specified variant, all of them will be updated.
data-cart-toggle
<label>
<input type="checkbox" data-cart-toggle="12345678" />
Include Gift Card
</label>
On a change
event, either add/remove the variant given by data-cart-toggle
to/from the cart.
data-cart-toggle-attribute
<label>
<input type="checkbox" data-cart-toggle-attribute="Is A Gift" />
This is a Gift
</label>
On a change
event, set the cart attribute specified by data-cart-toggle-attribute
to either "Yes
" or "" (a blank string).
data-cart-submit
<form action="/cart/add" method="post" data-cart-submit>
<input type="hidden" name="id" value="12345678" />
<button type="submit">Add to Cart</button>
</form>
On a form's submit
event, intercept the form submission and POST it via Ajax instead.
Note that this doesn't currently work with forms containing file uploads.
Events
Events are triggered on the document and prefixed with the cart
namespace.
See the Events section in the Guide for more.
cart.ready
Triggered after Cart.js has completed initialising.
$(document).on('cart.ready', function(event, cart) {
// Event handling here.
});
cart.requestStarted
Triggered whenever Cart.js begins to process the request queue.
Note that if you make multiple Ajax-triggered calls to Cart.js (say, two calls to addItem
in a row), this event will still only fire once.
$(document).on('cart.requestStarted', function(event, cart) {
// Event handling here.
});
cart.requestComplete
Triggered whenever Cart.js completes processing the current request queue.
Note that if you make multiple Ajax-triggered calls to Cart.js (say, two calls to addItem
in a row), this event will still only fire once at the end after processing all requests.
$(document).on('cart.requestComplete', function(event, cart) {
// Event handling here.
});
DOM Binding
DOM Binding is powered by Rivets.js, providing a flexible templating approach to cart rendering.
See the DOM Binding section in the Guide for more.
Rivets Binders
There are a number of binders you'll be working with, including rv-text
, rv-show
, rv-each-item
- a few of these are demonstrated in the DOM Binding section in the of the Guide, and a full breakdown of Rivets' available binders can be found under the Rivets docs Binder Reference.
Formatters
The general syntax for formatters looks similar to Liquid filters, with a couple of key differences. In generic form, it can be seen as
property | formatter
with the optional addition of arguments that can be passed to the formatter (note that Strings should be wrapped in quote marks). In contrast to Liquid filters, formatters with arguments are not separated by colons, e.g.
model.property | eq 'value'
eq
model.property | eq 'value'
Returns true
if the property matches the passed in value.
<div rv-show="item.title | eq 'Shirt'">
<!-- Element will be shown if the item's title equals 'Shirt' -->
</div>
includes
model.property | includes 'value'
Returns true
if the value
is present within the property
.
<div rv-show="item.title | includes 'Shirt'">
<!-- Element will be shown if the item's title includes 'Shirt' -->
</div>
This also works with arrays:
<div rv-show="item.variant_options | includes 'Blue'">
<!-- Element will be shown if the item's variant_options contain an element equalling 'Blue' -->
</div>
The includes
formatter is case-sensitive. For a case-insensitive option, see match
match
model.property | match 'regexp' 'flags'
Returns true
if the regexp
matches the given property
. To pass a regexp through Rivets, we need to provide the regexp as a String (without wrapping in /
), which will then be converted to a RegExp before evaluation.
The match
formatter evaluates and returns the value of the JS expression model.property.match(new RegExp(regexp, flags))
Basic example:
<div rv-show="item.title | match 'shirt|shoe'">
<!-- Element will be shown if the item's title matches the RegExp /shirt|shoe/ -->
</div>
Flags
Any flag you would normally provide as part of a JS RegExp (such as i
for case-insensitive), can be provided as part of an optional second argument.
<div rv-show="item.title | match 'shirt|shoe' 'i'">
<!-- Element will be shown if the item's title matches the RegExp /shirt|shoe/i -->
</div>
lt
model.property | lt value
Returns true
if the property is less than the passed in value.
<div rv-show="item.quantity | lt 5">
<!-- Element will be shown if the item's quantity is less than 5 -->
</div>
gt
model.property | gt value
Returns true
if the property is greater than the passed in value.
<div rv-show="item.quantity | gt 0">
<!-- Element will be shown if the item's quantity is greater than 0 -->
</div>
not
model.property | not
Returns an inversion of the passed in property
<div rv-show="item.requires_shipping | not">
<!-- Element will be shown if the item does not require shipping -->
</div>
This is particularly useful when chaining formatters e.g.
<div rv-show="item.variant_options | includes 'Blue' | not">
<!-- Element will be shown if the item's variant_options does not contain an element equalling 'Blue' -->
</div>
empty
model.property | empty
Returns true if the provided property has a length of 0
<div rv-show="item.product_description | empty">
<!-- Element will be shown if the item's product_description is blank -->
</div>
plus
model.property | plus value
Returns the result of parseInt(model.property) + parseInt(value)
.
<div rv-text="item.quantity | plus 1">
<!-- The value of the item's quantity, plus 1 -->
</div>
The plus
formatter casts both values to integers before performing the addition, so this is only suitable where both values will only be integers.
The plus
formatter will cast the provided value to an integer; therefore, it is important that a float is not used as the value.
minus
model.property | minus value
Returns the result of parseInt(model.property) - parseInt(value)
.
<div rv-text="item.quantity | minus 1">
<!-- The value of the item's quantity, minus 1 -->
</div>
The minus
formatter casts both values to integers before performing the subtraction, so this is only suitable where both values will only be integers.
The minus
formatter will cast the provided value to an integer; therefore, it is important that a float is not used as the value.
prepend
model.property | prepend 'value'
Returns the result of prepending the value to the property.
<div rv-text="item.title | prepend 'Title: ">
<!-- Title: { item.title } -->
</div>
append
model.property | prepend 'value'
Returns the result of appending the value to the property.
<div rv-text="item.title | append ' Text'">
<!-- { item.title } Text -->
</div>
money
model.property | money 'value'
Returns the property formatted with your store's currency formatting, allowing for an optional currency argument to be provided.
<div rv-text="item.price | money">
<!-- Formatted item price -->
</div>
If using the money
formatter, make sure that you have set the relevant options when initialising Cart.JS to provide your store's currency formatting (see Options: moneyFormat).
You will also need to include Shopify's option_selection.js
on all pages - see the note "Dependency when formatting monetary values" in the Guide for more detail.
money with currency
model.property | money_with_currency 'value'
Returns the property formatted with your store's currency formatting and the currency appended, allowing for an optional currency argument to be provided.
<div rv-text="item.price | money">
<!-- Formatted item price with currency -->
</div>
If using the money
formatter, make sure that you have set the relevant options when initialising Cart.JS to provide your store's currency formatting (see Options: moneyFormat).
You will also need to include Shopify's option_selection.js
on all pages - see the note "Dependency when formatting monetary values" in the Guide for more detail.
weight
model.property | weight
Returns the property converted to the weightUnit
set in the CartJS initializer (see Options: weightUnit).
<div rv-text="item.price | weight">
<!-- Item weight converted to set unit -->
</div>
If using the weight
formatter, make sure that you have set the relevant options when initialising Cart.JS to provide your store's weight unit (see Options: weightUnit), and required precision (see Options: weightPrecision).
weight with unit
model.property | weight_with_unit
Returns the property converted to the weightUnit
set in the CartJS initializer (see Options: weightUnit), with that unit appended onto the output (e.g. 0.5kg)
<div rv-text="item.price | weight">
<!-- Item weight converted to set unit, including unit -->
</div>
If using the weight
formatter, make sure that you have set the relevant options when initialising Cart.JS to provide your store's weight unit (see Options: weightUnit), and required precision (see Options: weightPrecision).
product image size
model.property | product_image_size 'size'
Returns the url for the provided image at the requested size (see Size Parameters for more info).
<img rv-src="item.featured_image | product_image_size 'small'" />