Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding $ vs. jQuery in iife instead of $

Tags:

jquery

iife

I am trying to understand if there is any difference between:

(function($){

...

})(jQuery);

vs.

(function($){

...

})($);

Note the jQuery was replaced with a $. Is this ok? Is it not used anywhere because it can't work? It works but maybe it is non-standard? Can someone please explain this if it is an error or if it is ok? Thanks

like image 447
Jason Avatar asked Jul 09 '12 21:07

Jason


3 Answers

Other JavaScript frameworks may also use $ as a shortcut. To guarantee that $ is jQuery inside your function, pass jQuery and not $ at the end. This type of defining a function or "code area" is to take sure that $ really is jQuery when mixing frameworks.

like image 96
Florian Brinker Avatar answered Oct 27 '22 17:10

Florian Brinker


Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():

http://api.jquery.com/jQuery.noConflict/

In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used. For example:

$(document).ready(function(){
     $(#somefunction) ...
});

Becomes:

jQuery(document).ready(function(){
    jQuery(#somefunction) ...
});

In order to use the default jQuery shortcut of $, you can use the following wrapper around your code:

jQuery(document).ready(function($) {
    // $() will work as an alias for jQuery() inside of this function
});

That wrapper will cause your code to be executed when the page finishes loading, and the $ will work for calling jQuery. If, for some reason, you want your code to execute immediately (instead of waiting for the DOM ready event), then you can use this wrapper method instead:

(function($) {
    // $() will work as an alias for jQuery() inside of this function
})(jQuery);

Good read: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_wrappers

Further if you keen:

What does $ mean in jQuery?

This should help to quench your thirst :) might be hope this helps!

like image 38
Tats_innit Avatar answered Oct 27 '22 15:10

Tats_innit


There is.
$ is just a shortcut for jQuery. It does not define the lib, therefore it may be used by other frameworks too.
Take this case into consideration :

// remove the jQuery shortcut ($ === undefined)
var j = jQuery.noConflict();
// redefine the dollar sign
window.$ = function(){
    // some other plugin
}

// case A
(function($){
   alert(jQuery === $);//true
})(jQuery)

 // case B
(function($){
   alert(jQuery === $);//false
})($)
like image 20
gion_13 Avatar answered Oct 27 '22 15:10

gion_13