Adding jQuery Support in Magento System

When you want to use some jQuery code, you need to add the jQuery library in your theme.

Posted on March 24, 2016 in Magento

By default, Magento loads the Prototype library. Excluding this will cause JavaScript errors on every page, so we need to use both libraries. The problem with jQuery and Prototype is that they both use the dollar sign ($) as the namespace for their functions.

To avoid the conflict, we have to use jQuery in the noconflict mode:

  1. Put the jQuery library in the skin/frontend/your_package/your_theme/js/jquery folder.

  2. Create a local.xml file in the app/design/frontend/your_package/your_theme/layout folder.

  3. Add the following content in that file:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <layout>
        <default>
            <reference name="head">
                <action method="addJs">
                    <js>jquery/jquery.js</js>
                </action>
            </reference>
        </default>
    </layout>
    
    

  4. Create a jquery.noconflict.js file in the skin/frontend/your_package/your_theme/js/jquery folder with the following content:
    
    $.noConflict();
    
    

  5. update the content in the local.xml as shown beblow:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <layout>
        <default>
            <reference name="head">
                <action method="addJs">
                    <js>jquery/jquery.js</js>
                </action>
                <action method="addJs">
                    <js>jquery/jquery.noconflict.js</js>
                </action>
            </reference>
        </default>
    </layout>
    
    

  6. Clear your caches and loo at the source of your frontend. The jQuery file and nocoflict.js file should be added in the head section

You can now use jQuery in your webshop. There are two things had to followed: 1) You have to call jQuery function with jQuery namespace instead of the $ namespace. 2) Third-party extensions of Magento could include jQuery in the frontend. Make sure the version is compatible with your code.

In the tutorial, we just added local.xml file. The main advantage of using a local.xml file for this is that you don’t have to overwrite an entire XML file from the base folder to add just two lines of code.


comments powered by Disqus