jQuery noConflict() method


jQuery - noConflict() method


How to use jQuery and other frameworks on the page at the same time?


jQuery and other JavaScript frameworks

As you have already learned, jQuery uses the $ sign as Abbreviation for jQuery.

What if other JavaScript frameworks also use the $ symbol as a shorthand?

Some other JavaScript frameworks include: MooTools, Backbone, Sammy, Cappuccino, Knockout, JavaScript MVC, Google Web Toolkit, Google Closure, Ember, Batman, and Ext JS.

Some of these frameworks also use the $ symbol as a shorthand (just like jQuery). If you are using two different frameworks that are using the same shorthand symbol, it may cause the script to stop running.

The jQuery team took this issue into consideration and implemented the noConflict() method.


##jQuery noConflict() method

noConflict() The method releases control of the $ identifier so that other scripts can use it.

Of course, you can still use jQuery by replacing the abbreviation with the full name:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$.noConflict();
jQuery(document).ready(function(){
  jQuery("button").click(function(){
    jQuery("p").text("jQuery 仍然在工作!");
  });
});
</script>
</head>

<body>
<p>这是一个段落。</p>
<button>点我</button>
</body>
</html>

Running Example »Click the "Run Example" button to view the online example

You can also create your own abbreviation. noConflict() returns a reference to jQuery that you can store in a variable for later use. Please look at this example:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
var jq=$.noConflict();
jq(document).ready(function(){
  jq("button").click(function(){
    jq("p").text("jQuery 仍然在工作!");
  });
});
</script>
</head>

<body>
<p>这是一个段落。</p>
<button>点我</button>
</body>
</html>

Run Instance»Click the "Run Instance" button to view the online instance

If your jQuery code block uses the $ abbreviation and you are unwilling to change this shortcut, you can pass the $ symbol as a variable to the ready method. This way you can use the $ symbol inside the function - but outside the function, you still have to use "jQuery":

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$.noConflict();
jQuery(document).ready(function($){
  $("button").click(function(){
    $("p").text("jQuery 仍然在工作!");
  });
});
</script>
</head>

<body>
<p>这是一个段落。</p>
<button>点我</button>
</body>
</html>

Run Instance»Click the "Run Instance" button to view the online instance