avoid jquery conflict with other javascript libraries

In this jQuery tutorial you will learn how to avoid jquery conflict with other javascript libraries. jQuery is a powerful javascript library. Using jQuery with other javascript libraries such as YUI, prototype or mootools, you may found conflict because they all use $ as their main function name and as a result jquery code will not run. To resolve this issue, jQuery has .noConflict() method. Let's have a look over the example given below


Avoid jquery conflict with other javascript libraries


<html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery.noConflict();
// Using jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery("someid").hide();
});


// Using Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body>Use of .noConflict() method of jQuery</body>
</html>



It will revert $ back to its original library.


Additionally, there is another option for you. If you want to make sure that jQuery won't conflict with other javascript libraries - but you want the benefit of a short name, you can do something like i have done below:

<html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script language="javascript" type="text/javascript">
var $hi = jQuery.noConflict();
// Using jQuery via $hi (...)
$hi(document).ready(function(){
//don't write other javascript libraries code in this region
$hi("div").hide();
});


// Using Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>

You can define anything as your own alternate name (e.g. hello, pakistan, cricket, jq).


Finally, if you don't want to define alternative to the jQuery name (you deadly want to use $ and don't care about using another library's $ method), then you have another solution. This is most frequently used in such case when you still want the benefits of really short jQuery code, but you don't want to cause conflicts with other javascript libraries.

<html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery.noConflict();


// Put all your jquery code in your document ready area
jQuery(document).ready(function($){
// don't write other javascript libraries code in this region
$("someid").hide();
});


// Using Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>

This is probably the perfect solution for most of your code, considering that there'll be less code that you'll have to change for getting complete compatibility of jquery with other javascript libraries. So these are the different techniques to avoid jquery conflict with other javascript libraries.

0 comments: