Reputation: 504
I just switched the way my wordpress theme loads jQuery from manually loading google's version to enqueuing the version that comes with wordpress. The version that comes with wordpress has "noconflict()" in it so the $ shortcut no longer works in all my jQuery and instead I need to use "jQuery" in it's place.
I have a lot of .js scripts and a lot of jquery setting initializations on pages and now none of it works because it was all using the shorthand $.
My question is, assuming I NEED to use the noconflict version that comes with wordpress, what is the best way to fix my shorthand code?
Should I add a line like this to the top of each script?
jQuery(document).ready(function($) {
or should I "Find in files" all $ and replace with jQuery?
Upvotes: 2
Views: 640
Reputation: 83356
You can use an immediately executing function to create a variable named $
which is set to jQuery
. This can simulate the behavior you had prior to switching over to noconflict
:
(function(){
var $ = jQuery;
//now use $ as you always have
})();
OR
(function($){
//now use $ as you always have
})(jQuery);
Upvotes: 1
Reputation: 34107
Wordpress recommendation: a good read http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_wrappers
http://api.jquery.com/jQuery.noConflict/
code
(function($) {
// $() will work as an alias for jQuery() inside of this function
})(jQuery);
Upvotes: 4
Reputation: 35409
You could pass into an immediately executing anonymous function the jQuery
object and any other API's\objects you want to work with inside the sandbox (function):
(function($, window, undefined) {
}(jQuery, window));
This mitigates the likely of conflicting code by locking in the implementation of jQuery
, undefined
and any other API that is essential to your code.
Upvotes: 2