Search code examples
javascriptjquerymagentomagento-1.9.1

How can I use jQuery on Magento 1.9.0.1 rwd theme?


I noticed Magento 1.9.0.1 rwd theme now include jQuery library and use "jQuery.noConflict();" associated on "$j" token on default.

First, I'ld like to use google CDN jQuery library instead of local jQuery library.

As second, how can run my jQuery code?

For example, I tried to insert in minicart.phtml:

    .....
       $_cartQty = 0;
    }
?>


<script type="text/javascript">
    $j(document).ready(function() {
        $('#header-cart').hide();
    });
</script>


<a href="#header-cart" class="skip-link skip-cart <?php if($_cartQty <= 0): ?> no-count<?php endif; ?>">
    <span class="icon"></span>
    ........

Also, I tried to use add my code at the end of app.js:

.....
};

$j(document).ready(function() {
    ProductMediaManager.init();
});

$j(document).ready(function() {
    $('#header-cart').hide();
});

but no effect. Where I wrong? How can I run my code in a separate file in app/js folder?


Solution

  • “First, I'ld like to use google CDN jQuery library instead of local jQuery library.”

    You should research more before asking easy questions, the following is taken from this post and this post. Overall I think it's not worth the extra effort just to rely on a 3rd party.

    In your theme's local.xml layout file add this.

    <default>
        <reference name="head">
            <action method="addItem"><type>skin_js</type><name>js/lib/jquery-1.10.2.min.js</name></action>
            <block type="core/text" name="google.cdn.jquery">
                <action method="setText">
                    <text><![CDATA[<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>window.jQuery||document.write('<script src="/skin/frontend/rwd/default/js/lib/jquery-1.10.2.min.js">\x3c/script>');</script>
    <script>jQuery.noConflict();</script>]]></text>
                </action>
            </block>
        </reference>
    </default>
    

    “As second, how can run my jQuery code?”

    $j(document).ready(function() {
        $('#header-cart').hide();
    });
    

    Here you know you must use $j instead of $ but you have forgotten that on the 2nd line! There are many ways to change it,

    1. Use $j everywhere:

      $j(document).ready(function() {
          $j('#header-cart').hide();
      });
      
    2. Rename $j using the function argument:

      $j(document).ready(function($) {
          // $ is different inside this function only
          $('#header-cart').hide();
      });
      
    3. Use Prototype instead:

      // $j is alias for jQuery
      $j(document).ready(function() {
          // $ is Prototype alias for document.getElementById
          $('header-cart').hide();
      });