jQuery noConflict()

jQuery noConflict() Method

As you know, jQuery uses the $ sign as a quick shortcut or alias for the word jQuery.

However, there are many other popular JavaScript frameworks out there.

Frameworks like Angular, Backbone, and Knockout also use the $ sign as a shortcut!


The Library Conflict Problem

If two different libraries are included on the same webpage, and both use the $ sign, things will break.

The browser won't know which library the $ belongs to, resulting in massive script errors.

Fortunately, the jQuery team anticipated this issue and created a built-in solution.


The $.noConflict() Method

The $.noConflict() method releases the hold on the $ shortcut identifier.

This allows other JavaScript scripts and libraries to safely use the $ sign.

After calling noConflict(), you can still use jQuery, but you must type out the full word jQuery.

The noConflict() Example:

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

Creating Your Own Shortcut

Typing out the full word jQuery every time can be tedious.

You can easily create your own custom shortcut by assigning $.noConflict() to a variable.

Custom Shortcut Example:

var jq = $.noConflict();
jq(document).ready(function(){
  jq("button").click(function(){
    jq("p").text("Using the custom 'jq' shortcut!");
  });
});

Passing the $ Sign as a Parameter

There is a smart trick to continue using the $ sign, even after calling noConflict().

You can pass the $ sign as a parameter directly into the ready function.

This allows you to use $ locally inside the function block, while external scripts use $ elsewhere.

Passing Parameter Example:

$.noConflict();
jQuery(document).ready(function($){
  // You can safely use $ here
  $("button").click(function(){
    $("p").text("Using $ safely inside the block!");
  });
});

Exercise 1 of 2

?

What is the primary purpose of the $.noConflict() method?

Exercise 2 of 2

?

Can you assign the noConflict() method to a custom variable name like 'myJq' to use instead of '$'?