I am fairly new to using jQuery in WordPress and I am trying to write jQuery scripts in a separate file.
What is the difference between the following two syntaxes of setting up the external file:
Version I
jQuery(function() {
jQuery("#radio").buttonset();
});
Version II
$(document).ready(function() {
$("#radio").buttonset();
}
1 Answer
jQuery.noConflict()
jQuery is included in WordPress in noConflict mode, so as to work with other javascript extensions that also use $
as an alias.
Hence your above Version II will not work with the WP native jQuery loading.
What is jQuery?
jQuery is not a language. It is nothing but a (massive) javascript object. That object’s name is jQuery
. When .noConflict()
is not applied, $
is an alias for the jQuery
object.
Best practice for external files
Wrap the entire js in a closure, pass it the jQuery
object and $
as an argument. Inside you can write your script the way you’re used to:
(function($){
$(document).ready(function() {
$("#radio").buttonset();
}
})(jQuery);