jQuery noConflict()
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery’s case, $ is just an alias for jQuery, so all functionality is available without using $.
$.noConflict() method can be used to relinquish jQuery’s control of the $ variable.
Using noConflict() with $ symbol
$ sybmol works as a shortcut for jQuery.
The $.noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.
As shown in below example, we can still continue to use the name “jQuery”
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $.noConflict(); jQuery(document).ready(function() { jQuery("#message1").text("jQuery still working"); try { $("#message2").text("$ still working"); } catch (err) { jQuery("#message2").text("$ no longer working"); } }); </script> </head> <body> <p id="message1"></p> <p id="message2"></p> </body> </html>
Creating our own shortcut for jQuery
Similar to $ symbol, we can create our own shortcut.
Lets create our own shortcut jqr as shown in below example :
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> jqr = $.noConflict(); jqr("#message1").text("jqr shortcut working"); </script> </head> <body> <p id="message1"></p> </body> </html>
Using $ even after calling noConflict()
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $.noConflict(); jQuery(document).ready(function($) { // $ will here $("#message1").text("$ still working inside function"); }); try { // $ for jQuery will not here $("#message2").text("$ still working"); } catch (err) { jQuery("#message2").text("$ not working outside"); } </script> </head> <body> <p id="message1"></p> <p id="message2"></p> </body> </html>
noConflict between two versions of jQuery loaded
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script> var log = $("#message"); log.append("2nd loaded jQuery version ($): " + $.fn.jquery + "<br>"); jqr = jQuery.noConflict(true); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> log.append("<h3>After $.noConflict(true)</h3>"); log.append("1st loaded jQuery version ($): " + $.fn.jquery + "<br>"); log.append("2nd loaded jQuery version (jqr): " + jqr.fn.jquery + "<br>"); </script> </head> <body> <div id="message"> <h3>Before $.noConflict(true)</h3> </div> </body> </html>
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post