Tuesday 20 October 2015

How to solve Jquery and Prototype conflicts in Magento.

Magento uses Prototype JS.Most of us prefer working with jQuery because of many reasons.So when we use Jquery in magento we get the error. this error is basically due to the conflict between prototype and jquery libraries.

When we call a jQuery with $ we will notice a conflict because Prototype.js also uses $ variable for itself whereas jQuery tries to register the variable causing conflict.So, if you have to use jQuery within a Magento store which rely heavily on Prototype.js just put your jQuery in compatibility mode.

The default call for jQuery function goes like this

$(document).ready(function(){
$("#someid").click(function(){

});
});

The above function will not work within a Magento store due to conflict with Prototype.js. You need to solve this conflict.

Instead follow the steps

1) Create one js file called noConflict.js with the following content.

var $j = $.noConflict();

and include this file after your jquery.js in the magento

2) And you can use this jquery wih the following code

<script type="text/javascript">
    $j(document).ready(function(){
        $j("#someid").click(function(){

});  
    });
</script>

Since we are using jQuery in compatibility mode it’s wiser not to call $ variable instead make a call to $j which is reference of jQuery.noConflict();. Simple isn’t it? Keep in mind that call to jQuery should be after the call to Prototype.

No comments:

Post a Comment