Creating a Magento Extension that uses a jQuery Plugin

While developing the DevoutGeek.com site, I created a number of Magento extensions. The first extension that I created was Configurable Colors. This extension creates color swatches in place of the color drop-down for configurable products. I created a jQuery plugin to display the color swatches and make ajax calls to the extensions controller method to display the relevant images. Through a bit of trial and error, I learned a great deal about creating Magento extensions (and incorporating jQuery into them).

There are many articles that discuss how to create Magento extensions, so this post discusses how to incorporate a jQuery plugin into the extension. For information on how to create an extension, read this.

Loading jQuery in the Layout

jQuery can be loaded in multiple locations. I use jQuery on multiple pages, not just for the Configurable Colors extension, so for personal projects, I add it to the page.xml file (/app/design/frontend///layout/page.xml).

<default translate="label" module="page">
      <label>All Pages</label>
      <block type="page/html" name="root" output="toHtml" template="page/2columns-left.phtml">
            <block type="page/html_head" name="head" as="head">
                ...
                <!-- load jquery last -->
                <action method="addItem"><type>skin_js</type><name>js/jquery-1.7.1.min.js</name></action>
            </block>
            ...
      </block>
</default>

Now copy the jQuery file into /skin/frontend///js/.

Note: If you plan to package the extension so that it can placed on magento-connect, you should include jQuery in your extension’s layout file. More on this later.

jQuery.noConflict()

Magento uses Prototype as it’s primary Javascript libarary, so in order for me to use $, I need to add jQuery.noConflict() before I call any jQuery methods. I forgot to add the noConflict call in the admin interface and received the following error:

Cannot call method ‘submit’ of undefined

I wrap all of my jQuery code in (document).ready and then I add the $ as a parameter to the anonymous function.

?View Code JAVASCRIPT
jQuery.noConflict();
jQuery(document).ready(function($) {
   //
   $(document.body).gpConfigurableColors();
});
Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks