Friday, May 29, 2015

JQuery : jQuery.noConflict(); Resolve the $ Conflict

The JQuery library by design uses only two global namespace so that it would not conflict with other JavaScript libraries.
  • $ - the dollar is used as a reference to JQuery namespace
    • Also used by Prototype library, YUI and mootools
  • jQuery - is also used to reference to jQuery namespace, this the more unique reference of the two options, but nobody really uses it
So what do you do if you wanted to use jQuey and Prototype on the same page?  Well jQuery can concede the $ sign to the other libraries with the code jQuery.noConflict() function

This sample code shows how jQuery gives up the $ sign to the JavaScript library Prototype


<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>JQuery No Conflict</title>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.2.0/prototype.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();

jQuery(document).ready(function(){
alert("jQuery still works!");
});
</script>
</head>
<body>
</body>
</html>


Note: The thing you have to remember is that the $ is no longer referring to JQuery, it now belongs to Prototype, if you try to use Prototype and JQuery on the same page without using jQuery.noConflict(), you will get a broken page with Prototype complaining that the $ does not work. However the error is not very description as you can see below in Firefox console.  You will get the TypeError: element.dispatchEvent is not a function.





Even though we've resolved the conflict, we are now left with type jQuery instead of using the $ every time we want to use jQuery.  Well we can assign the object jQuery to another shorthand variable with the code below.


<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>JQuery No Conflict</title>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.2.0/prototype.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();

var jq = jQuery;

jq(document).ready(function(){
alert("jQuery still works!");
});
</script>
</head>
<body>
</body>
</html>

The code above assigns the jQuery namespace to the variable jq. It's not as cool as the $, but at least it's less typing.

No comments:

Post a Comment