Jquery | $ is not defined - Solving JQuery Conflict

Author - Deepika
24.10.2017
|
0 Comments
|

Due to some project requirements sometimes we need to load multiple versions of jquery (not recommended). As most of the jquery library uses $ as an alias name for jQuery, therefore only $ of last library loaded into page works and if we try to use some functions from previous library using $ then it generates error because $ is having the reference of last library used on the page. That’s why sometime jquery does not work properly due to the conflict between two jquery libraries.

Example :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script src="local/jquery.js"></script>

<script>

$(document).ready(function(){

$(document).on("keypress", ".query", function() {

     if(event.keyCode == 13){

     $(".search").click();

     return false;

     }

     });

  });

</script>

This code causes jQuery error like ‘$ is not defined’.

Thus we need to use jQuery.noConflict() method in order to solve the problem.

Solution :
In this case we need to use some different variable name for the replacement of $.

Like This :

Var j =jQuery.noConflict();
Or
Var j$ =jQuery.noConflict();

Example:

j =jQuery.noConflict();
j(document).ready(function(){
j(document).on("keypress", ".query", function() {
if(event.keyCode == 13){
j(".search").click();
return false;
}
});
});

In this example, we are using j as an alias for jQuery instead of $.
Now we need not to refer the javascript library through $ as we have a different variable for that which will solve this conflict and will make it work.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *