Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery newbie: what does jQuery(function($) { ... }) means?

Tags:

I know in jQuery, $(callback) is the same as jQuery(callback) which has the same effect as $(document).ready().

How about

jQuery(function($) {   }); 

Can some one explain to me what does this kind of function mean?

What does it do?

what is the difference between this one and $(callback)??

what is the difference between this one and $(function())??

like image 459
Leem Avatar asked Jun 23 '11 13:06

Leem


People also ask

What does function ($) mean in jQuery?

(function($) { // do something })(jQuery); this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $ .

How can we use jQuery function in our code?

At its core, jQuery is used to connect with HTML elements in the browser via the DOM. The Document Object Model (DOM) is the method by which JavaScript (and jQuery) interact with the HTML in a browser. To view exactly what the DOM is, in your web browser, right click on the current web page select “Inspect”.

How do you define and call a function in jQuery?

Answer: Use the syntax $. fn. myFunction=function(){}


2 Answers

jQuery(function($) {  }); 

is the safest version of all three. It makes $ the local variable and thus gracefully avoids the conflicts with any other variables which possibly use $ symbol.

I think it was also added fairly recently, don't remember seeing it before.

These function all do the same things - execute some code when DOM is ready. $(document).ready(function(){}) is the original one, and it matches the underlying javascript API.

"$" and "jQuery" which accept function as an arguments were created as shortcuts to avoid repeating such a common construct. Accepting a function which accepts $ as its first argument is a further syntax sugar - now you get convenience of the closures without the need to do it yourself.

like image 180
George Karpenkov Avatar answered Oct 02 '22 12:10

George Karpenkov


  • $(function()) is a syntax error.
  • $() creates an empty jQuery object.
  • $(document).ready(function() { ... }) executes the given function when the DOM is ready
  • $(function() { ... }) is a shortcut for the same thing
  • jQuery(function($) { ... }) does so, too, but it also makes $ available inside the function no matter what it's set to outside.
like image 32
ThiefMaster Avatar answered Oct 02 '22 11:10

ThiefMaster