jQuery noConflict Mode
In this page:
What noConflict Does
Calling jQuery.noConflict() hands the global dollar symbol back to whichever library defined it first, preventing the two from overwriting each other.
Example: What noConflict Does
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
jQuery.noConflict();
console.log(typeof $);
</script>
</body>
</html>
Use jQuery Instead of Dollar
After calling noConflict(), the $ shortcut is released, so every selector in your code must be rewritten to use the full jQuery(...) name instead -- a small typing cost in exchange for avoiding library collisions.
Example: Use jQuery Instead of Dollar
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="msg">Hi</p>
<script>
jQuery.noConflict();
jQuery("#msg").text("Updated with jQuery()");
</script>
</body>
</html>
Create a Custom Alias
Assigning the return value of jQuery.noConflict() to a variable, like var $j = jQuery.noConflict(), lets you keep a short alias for jQuery without ever touching the global $ symbol at all.
Example: Create a Custom Alias
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="msg">Hi</p>
<script>
var $j = jQuery.noConflict();
$j("#msg").text("Updated with $j alias");
</script>
</body>
</html>
Use the Alias in Ready
That custom alias works everywhere you'd normally use $, including inside a document ready block -- $j(document).ready(...) behaves identically to $(document).ready(...) once $ has been reassigned elsewhere.
Example: Use the Alias in Ready
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="msg">Hi</p>
<script>
var $j = jQuery.noConflict();
$j(document).ready(function() {
$j("#msg").text("Ready fired using alias");
});
</script>
</body>
</html>
Avoid Library Conflicts
noConflict() matters most on pages that also load Prototype.js, MooTools, or other older libraries that also claim the $ symbol -- without it, whichever library loads last silently wins and breaks the other's code.
Example: Avoid Library Conflicts
<!DOCTYPE html>
<html>
<head>
<script>
window.$ = function() { return "other-library"; };
</script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
jQuery.noConflict();
console.log($());
</script>
</head>
<body></body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: