views:

69

answers:

3

Possible Duplicate:
what is difference of $(function(){ }); and $(document).ready(function() { }) ;?

what are the differences between $(document).ready(function() vs $(function(){
and should I write it in the $ form or the new jQuery(document).ready(function(){ way? if I have google api loaded is google.setOnLoadCallback(function() { a better way? or is it the same thing?

I've also seen people use $(function($){ can somebody help me, I'm lost. I bugs me when I don't know the code I write. I guess I should read through the library. Are the all being defined as the same thing?

+1  A: 
  • $(document).ready(function() {});
  • $(function() {});

The two statements are actually the exact same. So the second call is just a shortcut for the first.

The $ notation is again only a shortcut for jQuery. If you have loaded jQuery into your website you can use both. Especially if you don't load other JS librarys, which maybe also use the $ sign. That brings us to your mentioned

(function($){
}(jQuery));

call. What is done here is to make sure, that within your created function expression the $ sign references to the jQuery object. You're calling that anonymous function (which has $ as parameter) and pass the jQuery object in.

jAndy
+3  A: 

The two ways are equivalent, I personally prefer the second, $(function() {}); it's just a shortcut for document ready.

About the new jQuery(document)... construct, you don't really need to use the new operator, jQuery will use it internally if you don't.

The argument that the ready handler function receives, is the jQuery object itself.

That's quite useful where you have to run jQuery in compatibility mode with other libraries, for example:

jQuery(function ($) {
  // use $ here
});

The $ argument inside the callback will refer to the jQuery object, outside that function it might refer to another library like PrototypeJS.

CMS
+1  A: 

I encourage to read some articles that are very useful to understand somethings in jQuery ( and of course in javascript ), this articles explain how to create a jQuery plugin, but reading it you will understand some basic and important things, like closures witch is the meaning in this (function($){}(jQuery)); statement.

http://www.authenticsociety.com/blog/jQueryPluginTutorial_Beginner