noConflict
Release the $ shortcut when another library also uses it.
Syntax
var jq = jQuery.noConflict();Some libraries also use the $ name. jQuery.noConflict() gives $ back to them while keeping the full jQuery name available.
var jq = jQuery.noConflict();
jq("#box").hide();
// or scope $ safely inside a function
jQuery(function ($) {
$("#box").show();
});Example
Loading editor…
Press Run to see the result.
When to use it
- A WordPress site calls jQuery.noConflict() because WordPress loads jQuery with $ disabled by default to avoid Prototype conflicts.
- A legacy app includes both jQuery and MooTools; noConflict() gives $ back to MooTools and uses jQuery() instead.
- A plugin author wraps all plugin code in a self-executing function($ ) that receives jQuery to keep $ scoped safely.
More examples
Basic noConflict and alias
noConflict() restores $ to whatever owned it before jQuery loaded; the return value is jQuery itself under the alias $j.
<script>
var $j = jQuery.noConflict();
$j(function () {
$j("#msg").text("Running with $j alias.");
});
</script>IIFE to keep $ usable inside
Passing jQuery into an IIFE as parameter $ lets all internal code use the familiar $ shorthand without global conflict.
<script>
jQuery.noConflict();
(function ($) {
$(function () {
$("#banner").text("$ is safe here!");
});
}(jQuery));
</script>WordPress-style safe wrapper
WordPress passes jQuery as the $ parameter to .ready(), giving safe access within the callback without calling noConflict() explicitly.
<script>
jQuery(document).ready(function ($) {
$(".widget").hide();
$(".toggle-widget").on("click", function () {
$(".widget").toggle();
});
});
</script>
Discussion