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.
[Read more...]

About

Hi there, I'm Nithin. I'm a 23 year old web developer from India. I love technology, programming and the internet, and with this blog I'm hoping to be able to start some discussions about technologies that I work on or interest me, such as Ruby on Rails, Wordpress, jQuery and Web 2.0.

I'm currently working as a Ruby on Rails developer at an exciting new startup company called foradian, where I'm helping to develop a web based campus management system called fedena.
[Read more...]