Shopify Tutorial: Adding a Barchart for Inventory Using jQuery and JSON Objects

I was looking at t-shirts at an online store one day, and it had a nice little bar chart that displayed how much of each size it had left. I thought to myself, “I wonder if this is doable in Shopify?”. The answer is yes, thanks to jQuery and JSON Objects. In this tutorial, I’ll be showing you how to add a bar chart in your product page that shows how much of each variant you have left in a bar chart. A big thank you to Javascript wizard John Tajima for introducing me to JSON objects and helping me out with the Javascript portion of this tutorial.

Screen-shot-2009-11-22-at-6.13.52-PM

The bar chart integrated into the Moderno theme.

Implementing this feature can be done in three easy steps: adding the HTML/Liquid, adding the Javascript, and then adding the CSS. You can also fully customize the look of the bar chart with CSS. This bar chart will work for any theme, as long as you insert the HTML, Liquid, Javascript and CSS properly.

Keep in mind that this code will only work if you’re tracking the inventory levels of your product’s variant. In order to enable inventory tracking, you must navigate to your Product details page, and scroll down to where it lists the variants. Click the ‘edit’ link next to the variants, and in the dropdown menu, select “Shopify tracks this variant’s stock level”. Finally, enter the inventory level for this variant.

Screen shot 2009-12-10 at 12.09.34 AM

The way it works:

The algorithm is best explained with an example. You have a t-shirt with 3 variants: small, medium, large. Let’s say you have 2 smalls, 4 mediums, and 4 larges.

The Javascript code will first calculate the total inventory level for ALL variants – in this example, the total will be 10 (2 smalls + 4 mediums + 4 larges = 10). Then, for each variant, it will calculate the percentage of a single variant’s inventory level versus. the total inventory level. This percentage is then used to determine the width of each bar. The percentages in our t-shirt example would be 20% for small, 40% for medium, and 40% for large, and the CSS will fill in the black bars accordingly.

1. Download jQuery and put it in the theme.

If you are unsure of how to do this, please see Steps 1 to 3 from my last tutorial.

2. Insert the HTML/Liquid code inside of Product.liquid.

This is the code that is used to display the bar chart. Paste this code inside product.liquid where you want to output the bar chart.

{% if product.variants.size > 1 %}
  <div id="inventory">
    {% for variant in product.variants %}
      <div class="inventory-item">
        {{ variant.title }}<br/>
        <div class="inventory-bar">
          <div class="filler variant_{{forloop.index0}}">&nbsp;</div>
        </div>
      </div>
    {% endfor %}
  </div>
{% endif %}

The code above first checks if the product has more than one variant. The bar chart will only show if there is more than one variant, because there is not much point in making a bar chart if there is only one bar to show.

Next, the for-loop creates a div with the class “inventory-bar” for each variant. The “inventory-bar” div has a gray background has a width of 100% (which means that it will be the width of the “inventory” div. The div within “inventory-bar” is the black ‘filler’ bar that will expand its width depending on how much inventory for the variant is available. The filler bar is assigned a width in percentage by the Javascript in Step 3.

The next function then takes the inventory level of each variant, and assigns the CSS property ‘width’ in percentage. The percentage is calculated by dividing the variant’s inventory level by the total inventory, and then multiplying the result by 100. Using jQuery, the class variant_i (where ‘i’ is the index number of the loop) is assigned an inline style with the calculated width.

3. Insert the Javascript/jQuery code.

Below the code from Step 2, insert the following Javascript/jQuery code.

<script type="text/javascript">
jQuery(document).ready(function($){
  var product_json = {{ product | json }};
  // get total inventory of product
  var total_inventory = 0;
  jQuery.each(product_json.variants, function(i, v) { 
    total_inventory += v.inventory_quantity 
  });
  // replace inventory bars for variants
  jQuery.each(product_json.variants, function(i, v){
    var count = v.inventory_quantity;
    if (count == 0) {
      $('.variant_'+i).css({'background':'none'}).html('Sold Out');
    } else {
      $('.variant_'+i).css({'width': ((count / total_inventory)*100) + "%"});      
    }
  });
});
</script>

The code above first creates a JSON object of the product that you are currently viewing, using Liquid’s “json” filter. We want to convert the product into a JSON object because it will allow us to use Javascript for calculations (unfortunately, Liquid alone is not sufficient, as it does not have many math functions).

Next, it loops through each of the variants of the product, and calculates the total of all variant inventories and stores them in a variable called total_inventory.

The last function takes the inventory level of each variant, and assigns the CSS property ‘width’ in percentage. The percentage is calculated by dividing the variant’s inventory level by the total inventory, and then multiplying the result by 100. Using jQuery, the class variant_i (where ‘i’ is the index number of the loop) is assigned an inline style with the calculated width. The CSS class variant_i is matched up with the variant_{{forloop.index0}} in the for-loop from the HTML code in Step 2, which ensures that the right width is assigned to the right variant.

However, if the variant’s inventory level is 0, the bar for the variant will not be given a width, and instead it will display a message that says “Sold Out”.

4. Insert the CSS code.

Inside your CSS file, insert the following selectors for the bar chart.


#inventory{
        /*Give this div a width if you'd like to set the barcharts to a certain width. Otherwise, it will take on the width of its parent div. */
}

.filler{
	background:#000;
}

.inventory-item{
	margin-bottom:15px;
}

.inventory-bar{
	background:#e1e1e1;
	height:20px;
	width:100%;
}

The simple CSS above styles the bar chart. By using your own CSS, you can customize the color, margin, width, etc. in any way that you like.

Here are some examples of the bar charts in action, in different themes:

dropify2

The bar chart in the Dropify theme.

minimify

The bar chart in the Minimify theme.

Conclusion:

Originally, I had wanted to use just Liquid to accomplish this, but in the end I had to use a combination of Liquid and Javascript because Liquid cannot do many math functions. With that said I’m pretty happy that I used Javascript because I learned a great deal about JSON objects. (thanks again John!). I hope you find this technique useful, and I hope to see this in some themes in the future!

25 comments

Leave a Reply: