jQuery - The noConflict() Method


What if you wish to use other elements in your pages, while using jQuery?


jQuery and Other JavaScript Frameworks

As you already know; JQuery uses the $ symbol as a jQuery shortcut.

There are many other popular JavaScript frameworks such as: Angular, Backbone, Ember, Knockout, and more.

What if other JavaScript frameworks also use the $ sign as a shortcut?

If two different components use the same shortcut, one of them may stop working.

The jQuery team has already considered this, and used the noConflict() method.


The jQuery noConflict() Method

The noConflict() method frees up the grip of the $ shortcut identifier, so that other scripts can use it.

You can still use jQuery, by typing the full name instead of the shortcut:


Example
$.noConflict();
jQuery(document).ready(function(){
  jQuery("button").click(function(){
    jQuery("p").text("jQuery is still working!");
  });
});

You can also create your own shortcut very easily. The noConflict() method returns the reference to jQuery, which you can save in a variable, for later use. Here is an example:


Example
var jq = $.noConflict();
jq(document).ready(function(){
  jq("button").click(function(){
    jq("p").text("jQuery is still working!");
  });
});

If you have a jQuery code block that uses the $ shortcut and you do not want to change it all, you can transfer $ login as a parameter in the correct direction. This allows you to access jQuery for $, within this function - without it, you will need to use "jQuery":


Example
$.noConflict();
jQuery(document).ready(function($){
  $("button").click(function(){
    $("p").text("jQuery is still working!");
  });
});