Skip to main content

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.

addItems

CartJS.addItems(items, options = {})

Adds the provided items to the cart. You can specify multiple lines, each with their own custom properties.

// Add 3x 12345678 items and 2x 87654321 items.
CartJS.addItems([
  {
    id: 12345678,
    quantity: 3,
    properties: {
      "size": "XL"
    }
  },
  {
    id: 87654321,
    quantity: 2
  }
]);

See addItem for details on the options hash.

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

Full documentation for the DOM Binding module is coming soon.

In the meantime, you can check out the example on the front page in combination with the Rivets.js documentation to get an idea of how things work.