Monthly Archives: December 2012

Using jQuery with Magento

When it comes to JavaScript libraries, I prefer jQuery over Prototype. This becomes problematic when I try to include jQuery libraries and plugins with Magento because Magento relies heavily on Prototype. Even when I include a call to jQuery.noConflict() and wrap my code in closures, I still get a script error with Internet Explorer 7 and 8: “Object doesn’t support this property or method”.

I solved this problem by rearranging my JavaScript includes. Basically, include the jQuery library and a call to jQuery.noConflict() before including the Prototype library and include your custom code that uses jQuery to the end of the JavaScript includes.

1. Create a jquery folder under Magento’s top-level js directory

2. Put the jQuery .js file in js/jquery

3. Create a .js file named noconflict.js in js/jquery. The only contents of that file are:

jQuery.noConflict();

4. Add the jQuery and noconflict scripts to the page layout. In your theme’s layout/page.xml file, update the “head” block and add the addJs lines to the top before the addJs lines for prototype:

<action method="addJs"><script>jquery/jquery-1.8.2.min.js</script></action>
<action method="addJs"><script>jquery/noconflict.js</script></action>

5. Add any additional custom scripts to the end of the list. But make sure they are enclosed in enclosures:

(function($){
// your custom code that uses jQuery here
})(jQuery);