Using the jQuery library

I will be using the jQuery library in this tutorial, but you should use any JavaScript library you know well. Work with what you know and love. If you don't really know any library, I strongly recommend using jQuery because it is easy to learn and light-weight. The latest release of jQuery on this day (August 28th, 2008) is 1.2.6. But go ahead and download the latest release, whichever it is — at the time you read this.

You will need to upload the library to your Shopify theme Assets directory.

Once you've done this, you will be able to link to it from your theme.liquid template, by adding the Liquid Output {{ 'jquery-1.2.6.min.js' | asset_url | script_tag }} to the head element of your XHTML document, like so:

{{ 'jquery-1.2.6.min.js' | asset_url | script_tag }}

Your theme may already use an other library like Prototype or Mootools. That's not a problem, as you can force jQuery to play nice with other JavaScript libraries. To make it play nice, all you need to do is add one line of JavaScript code in your theme.liquid template, and then use the jQuery namespace whenever you'll use the jQuery object.

{{ 'jquery-1.2.6.min.js' | asset_url | script_tag }}
<script type="text/javascript"> 

This effectively gives the use of the alias $ back to JavaScript libraries that make use of it. And then you can write jQuery code in any template without conflict. Of course, you will have to leave the $ alias alone! Unless you write code to be understood by another library that makes use of the alias. For the full, technical explanation, head over here.

We are now ready to implement our JavaScript solution. But first, we'll write XHTML to add two drop-down select elements to the Add to Cart form in our product template.