Examples

The following examples showcase various simple ways to use the JavaScript Buy SDK to build ecommerce into a website.

Setup

To use any of the examples, we first have to set up a Shopify Client in our JavaScript. Head over to Getting started for more details.

$(function() {
  var client = ShopifyBuy.buildClient({
    accessToken: 'your-access-token',
    domain: 'your-shop-subdomain.myshopify.com',
    appId: '6'
  });
});

Product Checkout

This example illustrates the simplest way to integrate ecommerce into your site to allow the purchasing of a single product. It creates an HTML anchor element that links to the product’s checkout URL.

We are going to create our markup in our JavaScript, therefore our HTML can just include a container element.

<div class="product" id="product-1"></div>

After fetching a product with the product ID we use the promise function to generate some markup with the required attributes and content, and add it inside our HTML container element.

client.fetchProduct('your-product-id').then(function(product) {

  var html =
  "<img class='product__image' src='" + product.selectedVariantImage.src + "' >" +
  "<h2 class='product__title'>" + product.title + "</h2>" +
  "<a class='product__buy' href='" +
    product.selectedVariant.checkoutUrl(1) +
  "'>Buy Now!</a>";

  $('#product-1').html(html);

});
.product {
  max-width: 400px;
  box-shadow: 0 0 15px 5px #eee;
  padding: 30px;
}

.product__buy {
  background: #7ab55c;
  padding: 0.5625em 1.875em;
  color: white;
  text-decoration: none;
  border-radius: 3px;
  display: inline-block;
}

.product__buy:hover {
  text-decoration: none;
  background: #6aa74c;
}

Product Add-To-Cart

This example illustrates the use of a cart to manage multiple products and variants. Only certain snippets of code will be highlighted from the full example available in a subfolder in the JS Buy SDK repository.

First, the app makes a call to retrieve the product. Then, it sets a few variables to store the default selected variant, the selected variant’s image and the variant options available for the product.

var selectedVariant = product.selectedVariant;
var selectedVariantImage = product.selectedVariantImage;
var currentOptions = product.options;

The demo then updates the HTML structure for the product using the updateProductTitle, updateVariantImage, updateVariantTitle, and updateVariantPrice functions, and builds out <select> elements for the product’s variant options and appends them to the product’s HTML markup.

var variantSelectors = generateSelectors(product);
$('.variant-selectors').html(variantSelectors);
function generateSelectors(product) {
  var elements = product.options.map(function(option) {
    return '<select name="' + option.name + '">' + option.values.map(function(value) {
      return '<option value="' + value + '">' + value + '</option>';
    }) + '</select>';
  });

  return elements;
}

Various listener functions are called to watch for ‘Add to Cart’ button clicks, variant option changes, and increment/decrement buttons for the variants in the cart. The attachOnVariantSelectListeners function updates the product.options when an a selected option is changed, then calls the various update functions with the new selected variant and selected variant’s image.

function attachOnVariantSelectListeners(product) {
  $('.variant-selectors').on('change', 'select', function(event) {
    var $element = $(event.target);
    var name = $element.attr('name');
    var value = $element.val();
    product.options.filter(function(option) {
      return option.name === name;
    })[0].selected = value;

    var selectedVariant = product.selectedVariant;
    var selectedVariantImage = product.selectedVariantImage;
    updateVariantImage(selectedVariantImage);
    updateVariantTitle(selectedVariant);
    updateVariantPrice(selectedVariant);
  });
}

In our example application when a product variant is added to the cart, the addVariantToCart function handles a series of things. First, it updates the cart model. It then uses the line items in the cart to build the required markup to display the cart items in the DOM.

...

var $cartLineItems = checkout.lineItems.map(function (lineItem, index) {
  var $lineItemTemplate = $(lineItemEmptyTemplate);
  var itemImage = lineItemImages[lineItem.variant_id];
  $lineItemTemplate.find('.cart-item__img').css('background-image', 'url(' + itemImage + ')');
  $lineItemTemplate.find('.cart-item__title').text(lineItem.title);
  $lineItemTemplate.find('.cart-item__variant-title').text(lineItem.variant_title);
  $lineItemTemplate.find('.cart-item__price').text(formatAsMoney(lineItem.line_price));
  $lineItemTemplate.find('.cart-item__quantity').attr('value', lineItem.quantity);
  $lineItemTemplate.find('.quantity-decrement').attr('data-variant-id', lineItem.variant_id);
  $lineItemTemplate.find('.quantity-increment').attr('data-variant-id', lineItem.variant_id);

  if (!existingLineItem && (index === checkout.attrs.line_items.length - 1)) {
    $lineItemTemplate.addClass('js-hidden');
  }
  return $lineItemTemplate;
});
$cartItemContainer.append($cartLineItems);

...

Show/Hide Cart

Additional event listeners are used to toggle the cart’s visibility on/off by adding and removing the js-active class on the cart.

function openCart() {
  $('.cart').addClass('js-active');
}

function closeCart() {
  $('.cart .btn--close').click(function () {
    $('.cart').removeClass('js-active');
  });
}

Your cart

Total
CAD
Shipping and discount codes are added at checkout.