user2105735
user2105735

Reputation: 55

How to convert jquery into noconflict?

I have an issue on a Wordpress site where the theme has a large init.js file that seems to be causing conflicts with some plugins.

Disclaimer, I'm a total noob, but I'm thinking that I would need to convert the below chunk of code into noconflict mode, but the few things that I have tried do not seem to work.

jQuery(document).ready(function(){

    $ = jQuery; 

Is it possible to convert that code into noconflict?

Upvotes: 0

Views: 119

Answers (3)

Vipin Choubey
Vipin Choubey

Reputation: 345

You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var jq = $.noConflict();
jq(document).ready(function(){
  jq("button").click(function(){
    jq("p").text("jQuery is still working!");
  });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<button>Test jQuery</button>

</body>
</html>

As Described in W3schools.com

Upvotes: 1

Madhuri Patel
Madhuri Patel

Reputation: 1270

You have add jQuery.noConflict() after ready function and then start your logic. Example:

jQuery(document).ready(function(){

$ = jQuery;
$.noConflict();

//Your logic

});

Upvotes: 0

T&#226;n
T&#226;n

Reputation: 1

You can use IIFE to do that:

(function ($) {
    console.log(typeof $);
    
    $(document).ready(function () {
        console.log($('body')[0]);
    });
})(typeof $ === 'function' ? $ : jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


If you're using webpack, you may need to check global object first:

(function (global, factory) {
    factory(typeof global.$ === 'function' ? global.$ : global.jQuery);
})(typeof window === 'object' ? window : this, function ($) {
    console.log(typeof $);

    $(document).ready(function () {
        console.log($('body')[0]);
    });  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions