0

What does the following code structure do?

(function($){
   // Some code
})(jQuery);

I've encountered this structure here.

Edit

As a reference to myself:

jQuery is the same as $ in your jQuery scope. Other libraries than jQuery often have the character $ defined as well. Someone might want to use another js library next to jQuery(e.g. Mootools). In order to let them work together you should undefine or redefine $.

The following line undefines $ in jQuery:

jQuery.noConflict();   

The following line redefines $ as $jq in jQuery:

var $js = jQuery.noConflict();

When you use the code structure (function($){ // Some code })(jQuery); you are guaranteeing the jQuery code //Some code to work even is someone called that code in a scope where $ is undefined.

Also see Tats_innit's answer here.

Community
  • 1
  • 1
Bentley4
  • 10,678
  • 25
  • 83
  • 134

2 Answers2

3

This is for compatibility, to avoid that jQuery uses the $ and, by doing so, leave it free for other frameworks.

This function uses jQuery as parameter, so inside the function's scope the $ will have jQuery's methods that you can call by the $ (dollar sign).

Mootools and Prototype use also the dollar sign.

Sergio
  • 28,539
  • 11
  • 85
  • 132
0

It will run some functions when your page is loaded into the browser.

Hope you already refered jQuery, if not start here How jQuery Works

Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120