jQuery: Avoiding conflict with other libraries using jQuery.noconflict()

Recently, when using jQuery in my Ruby on Rails project, the jQuery calendar plugin I was using suddenly refused to work in one of the views. The plugin was working fine everywhere else, but it just wouldn't work here.

The problem was that there was a conflict with a rails prototype helper (observe_field) that I was using in the view. Using jQuery along with other javascript frameworks such as prototype or mootools causes a namespace clash as they all use the $ alias.

jQuery provides a noconflict method to avoid this clash, which lets you rename the jQuery function ($) as something else.

In the code below, the noconflict method is called to replace the $ alias with the function name jQuery and release $ to other frameworks.

<script src="jquery.js"></script>
<script>
  jQuery.noConflict();
  jQuery(document).ready(function(){
    // your code goes here.
  });
</script>

However, you can also use some other name instead of jquery by assigning jQuery.noconflict() to another variable. In the code below, I have use $jq as the new alias for the jQuery function. Now you must use this new alias where you would otherwise have used the $ shorthand.

<script src="jquery.js"></script>
<script>
  var $jq = jQuery.noConflict();
  $jq(document).ready(function(){
    // your code goes here.
  });
</script>

Using this form of the noconflict method allows you to avoid namespace conflicts while at the same time giving you the ability to use a short alias ($jq above) for jQuery.

If you want to globally disable the $ alias for jQuery, call the noconflict method from the last line of the jQuery file.

Make sure you call this function before using the conflicting library, otherwise it may still clash. However, you may include the other library without causing any conflict.

1 comments:

Arowolo said...

this is brilliant. works like a charm

Post a Comment