How to use jQuery in Magento
I was recently working with Magento and found that I needed to use jQuery library sometimes.
Since Magento uses Prototype for the JavaScript library, I thought it would be good to write a tutorial on how to use jQuery with Magento.
There are two options :
- Use the local jQuery library
- Use the Google AJAX Libraries CDN (Content Delivery Network)
Option1: Use the local jQuery library
- Upload the jQuery file (jquery.js) to your skin folder. In my case, I created a new directory called "js"
/skin/frontend/default/new_theme/your_theme/js - To include this jQuery file, open your page layout file (page.xml) from your theme folder and add the following line to the header block
<action method="addJs"><script>js/jquery.js</script></action> - Since Prototype does not get along with jQuery well, we will have to include jQuery.noConflict(); function to prevent conflicts
The code would look like this
<script> jQuery.noConflict(); jQuery(document).ready(function(){ jQuery("#test").hide(); }); </script>
For more information about jQuery.noConflict(); function, please refer http://api.jquery.com/jQuery.noConflict/
Option2: Use the Google AJAX Libraries CDN
- Since external URLs cannot be included in the layout files (e.g. page.xml) of Magento, we will need to add the jQuery library in the design template
In this case, I will add the following line into head.phtml like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script> - Like Option1, we will need to include jQuery.noConflict(); function to prevent conflicts. Please see step3 on Option 1 to add the function.