Saturday, November 7, 2009

jQuery.noConflict()

There are different JavaScript libraries such as jQuery,mootools,ajax etc available which helps us to add functionalities to our web applications.
Hundreds of plugins built using those libraries are making our tasks easy. So without actually peeping into the code we use those plugins.
Now, the problem arises when these libraries are used together.

I stuck in the same problem when I was implementing jquery in my application which already had lighbox implemented in it.
After researching a lot I figured out that prototype.js which was used for implementing Lightbox and jQuery.js in my application were conflicting.

The real problem was both libraries were using '$' as their main function name. Hence one library was breaking the behaviour of other library.

for e.g. in jquery we use :
$(function(){
---
---
});

Here '$' represents jQuery. Similarly in prototype.js for lightbox '$' was used which was representing its main function.
jQuery has provided us the solution to get rid of this problem. Simply use noConflict() function immediately after jQuery.js.
When you use noConflict(), jQuery will return $() to its previous owner and you will need to use jQuery() instead of shorthand $() function.

so it can be written as
jQuery(function(){
---
---
});

else...

var j=jQuery.noConflict();

so,
j(Function(){
--
--
});

So now, jQuery is compatible with other javascript libraries and can be used easily.