jQuery - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

jQuery noConflict

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] <html> <head> <title>jQuery noConflict()</title> </head> <body> <h1>Welcome to SPLessons</h1> <div> <p>click on this paragraph</p> </div> </body> </html> [/html] [javascript] $.noConflict(); jQuery(document).ready(function() { jQuery("p").click(function() { alert("Paragraph was clicked"); } } [/javascript] 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] <html> <head> <title>jQuery noConflict()</title> </head> <body> <h1>Welcome to SPLessons</h1> <div> <p>click on this paragraph</p> </div> </body> </html>[/html] [javascript] var jQ = $.noConflict(); jQ(document).ready(function() { jQ("p").click(function() { alert("Paragraph was clicked"); }); }); [/javascript] 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] <html> <head> <title>jQuery noConflict()</title> </head> <body> <h1>Welcome to SPLessons</h1> <div> <p>click on this paragraph</p> </div> </body> </html> [/html] [javascript] $.noConflict(); jQuery(document).ready(function($) { $("p").click(function() { alert("Paragraph was clicked"); }); }); [/javascript] 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.