jQuery - SPLessons
boy2 Chapter 13

jQuery noConflict

jQuery - SPLessons

jQuery noConflict

shape Introduction

The $ sign is used to define jQuery. So many other JavaScript frameworks like Angular, Backbone, Ember, Knockout and more also uses shortcode$.

If other frameworks also use $ as shortcode, the script will not work. To avoid this, jQuery team implemented noConflict() method.

The jQuery noConflict() Method

shape Description

The noConflict() method holds on the $ shortcut identifier, so that other scripts can use it and can write full name jQuery instead of shortcut $.

<html>
<head>
   <title>jQuery noConflict()</title>
</head>

 <body>
 
   <h1>Welcome to SPLessons</h1>
   <div>
      <p>click on this paragraph</p>
   </div>
   
   
  </body>
</html>

$.noConflict();
jQuery(document).ready(function()
{
      jQuery("p").click(function()
{
        alert("Paragraph was clicked");
      }
   }

Output:

shape Alternative
forms

Even own shortcut can be written very easily.The method noConflict() returns a reference to jQuery, and can save it in a variable.

<html>
<head>
   <title>jQuery noConflict()</title>
</head>

 <body>
 
   <h1>Welcome to SPLessons</h1>
   <div>
      <p>click on this paragraph</p>
   </div>
   
   
  </body>
</html>

var jQ = $.noConflict();
jQ(document).ready(function() {
      jQ("p").click(function() {
        alert("Paragraph was clicked");
      });
   });

Output:

shape Alternative
form

$ shortcode can be passed as a parameter to the method “ready”. It enables to get to jQuery utilizing $, inside this function – outside of it, and need to utilize “jQuery”:

<html>
<head>
   <title>jQuery noConflict()</title>
</head>

 <body>
 
   <h1>Welcome to SPLessons</h1>
   <div>
      <p>click on this paragraph</p>
   </div>
   
   
  </body>
</html>

$.noConflict();
jQuery(document).ready(function($) {
      $("p").click(function() {
        alert("Paragraph was clicked");
      });
  });

Output:

Summary

shape Key Points

  • To avoid the usage of $ along with other JavaScriptt frameworks, jQuery team implemented noConflict() method.
  • jQuery is used instead of shortcut $.
  • $ shortcode can be a parameter to ready method.