Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / jQuery

What is JQuery.noConflict?

4.67/5 (5 votes)
26 Oct 2014CPOL1 min read 8.8K  
What is JQuery.noConflict?

As per official jQuery, we can define JQuery.noConflict as “A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).”

In most of the web development software, we used client side scripting [reference: http://en.wikipedia.org/wiki/Client-side_scripting].

Magic is most of these scriptting adapted JavaScript. This is not false if I say JavaScript is a mother language of most client-scripting :).

Let's come back to our original question, many of JavaScript libraries mostly use $ as a function or variable name [reference: http://api.jquery.com/jQuery.noConflict/].

In similar way in JQuery, we use $ as an alias of jQuery, which is nothing but provides us all functionality without using $.

Now, think about a situation where you need to use different types of client-scripting, see the below snippet:

PHP
<script src="myjavascriptlibrary.js"></script>
<script src="mycustomlibrary.js"></script>
<script src="myjquery.js"></script>

<script>
//Here I am using my customlibrary alongwith other Javascrip libraries
</script>

<script>
//Here I am using my customlibrary alongwith other Javascrip libraries
</script>

In the above scenario, render-engine has no idea to detect the owner of $, so, the above will not run successfully.
So, what to do to make it correct, think for following in a moment:

PHP
<script src="myjavascriptlibrary.js"></script>
<script src="mycustomlibrary.js"></script>
<script src="myjquery.js"></script>

<script>

$.noConflict();
//Write code for all custom libraries including jquery itself

</script>

It's too easy to use, isn’t it!

Here are some more ways to use noConflict() along with jquery itself:

PHP
//You can separate jquery path
<script src="myjavascriptlibrary.js"></script>
<script src="mycustomlibrary.js"></script>
<script src="myjquery.js"></script>

<script>

$.noConflict();

jQuery( document ).ready(function( $ ) {

//Write code for jquery

});
//Write code for all custom libraries

</script>
PHP
//You can get a jquery alias to teart a separate copy
<script src="myjavascriptlibrary.js"></script>
<script src="mycustomlibrary.js"></script>
<script src="myjquery.js"></script>

<script>
//jquery in my own copy
var $myjq = jQuery.noConflict();

</script>

Reference(s)

The above is a prescribed way to understand the answer, if you are willing to get into depth, you can refer to the official jquery docs: http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)