Error: $ is not a function or how to resolve conflicts with other javascript libraries that use $() function

One of the reasons that make a jQuery popular is its extensions and plugins. Some CMS also include the jQuery library such as WordPress.

Plugins let easily add functionality to a website and sometimes one might include more than one JavaScript Libraries (Prototype, jQuery, Mootools, etc).  If you have more than one library it might brake the behavior of the first one.

When you use the function jQuery.noConflict() it will return $() to it’s previous owner and you will need to use jQuery() instead of shorthand $() function.

jQuery.noConflict();
jQuery(document).ready(function(){
jQuery("#someid").hide();
});
// Now you can use Prototype or other libraries with $(...)
$('someid').hide();

Tip: you can shorten this by assigning jQuery to a variable name. Example: var $j = jQuery;

Another case is when  you have a bunch of javascript/jQuery code (small scripts or plugins) that’s already written to use the $, and you don’t want to search and replace the $ with jQuery.

jQuery(document).ready(function($){
// Inside this block you use the $ of jQuery
// not the other $
});
This entry was posted in JS and tagged , , .

Leave a Reply

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