Thursday, November 20, 2014

Using jQuery in Magento

Method 1:

Magento Community Edition 1.9 come with a new theme named rwd that implements Responsive Web Design (RWD) practices. This guide discusses what you need to know when customizing your own responsive theme.

Magento CE's and EE's responsive theme uses a number of new technologies:

  • Sass/Compass: A CSS pre-compiler that provides organizable, reusable CSS.
  • jQuery: Used for all custom JavaScript in the responsive theme. jQuery operates in noConflict() mode so it doesn't conflict with Magento's existing JavaScript library.
  • Additional JavaScript libraries discussed in more detail in Working With JavaScript.

# grep -i 'jquery' app/design/frontend/rwd/default/layout/page.xml

# grep 'jQuery.noConflict' skin/frontend/rwd/default/js/app.js
var $j = jQuery.noConflict();

http://www.magentocommerce.com/knowledge-base/entry/ee114-ce19-rwd-dev-guide

Method 2:

1. Save jquery-2.1.1.min.js and jquery-2.1.1.min.map to:

js/jquery2.1.1/jquery-2.1.1.min.js
js/jquery2.1.1/jquery-2.1.1.min.map

2. Add the following line to the end of this js/jquery2.1.1/jquery-2.1.1.min.js file:

# vim js/jquery_var.js

var $j = jQuery.noConflict();

Note: because Magento also includes Prototype, there is a subtlety we need to deal with. jQuery uses '$' as shorthand for accessing the jQuery library. But Prototype also uses '$' to access itself. This causes a conflict in the global JavaScript namespace of the web browser. Fortunately jQuery provides a solution, the jQuery.noConflict(); function defines a new shorthand for jQuery.

Note: The above code needs to come after the jQuery library code, but before any other JavaScript libraries. You can include the noConflict call at the bottom of the jQuery file you have copied to the js directory. Therefore you need make sure that "action method" line we included in layout/page.xml comes before the code that includes Prototype or any other JavaScript libraries.

3. Add the following lines to app/design/frontend/mycustom/default/layout/page.xml:

<action method="addJs"><script>jquery2.1.1/jquery-2.1.1.min.js</script></action>
<action method="addJs"><script>jquery_var.js</script></action>

Before this line:

<action method="addJs"><script>prototype/prototype.js</script></action>

4. Add the following lines to app/design/frontend/mycustom/default/template/page/test.phtml:
<a href="#" id="testBtn">gan</a>
<script>
$j(document).ready(function() {
  $j('#testBtn').click(function(e){
    console.log('asdf');
  });
});
</script>

5. create a new CMS page, with URL key called test

6. put this line in the CMS page:
{{block type="core/template" template="page/test.phtml"}}

7. access your page: http://mysite.com/test

http://www.fontis.com.au/blog/magento/using-jquery-magento

No comments: