One of the reasons that make a software popular is its extensions and plugins. jQuery has plenty of plugins that do almost anything you want, from simple button hide to full blown galleries. Plugins let non developers easily add functionality they need to their websites and there are times when one might include more than one javascript library such as prototype.js, YUI or mootools with jQuery. They all use $ as their main function name. Including second library might brake the behavior of the first one. To resolve such cases jQuery introduces .noConflict() method.
When you call .noConflict() jQuery will return $() to it’s previous owner and you will need to use jQuery() instead of shorthand $() function.
.noConflict() usage example (From jQuery Docs site)
<html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery("div").hide();
});
// Use Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>
You can also use the following code snippets to still use $() in your code, but with one drawback, you will not have access to your other library’s $() method.
// Method 1
jQuery(document).ready(function($){
$("div").hide();
});
// Method 2
(function($) {
/* some code that uses $ */
})(jQuery);
TIP:
Don’t forget that you can always assign jQuery to any other variable name to use it as your shorthand: var $_ = jQuery;
4 comments:
Hi, I was wondering if you could help me with a conflict on my site.
I have a menu that uses jQuery, and a script (LightView) running prototyp.
Ive researched the conflict, and tried to understand how to fix it, but I'm pretty much lost.
I dont know where to properly use .noConflict()
Could you take a look at mysite and maybe suggest a solution?
My email is squirrelslax[at]gmail.com
thank you
This doesn't tell you how to use other libraries.
Thank you! it works!)
Post a Comment