Possible Duplicate:
What is the meaning of “$” sign in javascript
what difference does the $
at the beginning of anonymous function?
This Example:
(function() {
...
})();
Versus this one:
$(function() {
...
})();
Possible Duplicate:
What is the meaning of “$” sign in javascript
what difference does the $
at the beginning of anonymous function?
This Example:
(function() {
...
})();
Versus this one:
$(function() {
...
})();
(function() {})();
The line above is creating an anonymous function and then executes it right away
$(function() {})();
Assuming you have jQuery loaded, the line above causes an error. This part $(function(){}) will pass an anonymous function into jQuery that gets run. jQuery will return a Document object back to you. Because you have the ending parenthesis () the Javascript will try to execute the Document object as a function. Because the Document object is not a function, a TypeError exception will be raised.
Taken from the jQuery website:
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():
You can read all about it here.
This as also been covered before at this and this stackoverflow questions!
like all the other answers state
$(function(){
...
});
is really just
jQuery(function(){
});
and the second will work the same, the difference between that and the other type of function of put in your example is that the first has to be called from somewhere , where as the jQuery version - if jQuery is loaded in HTML it will automatically run when document ready.
Your first example is a self-executing function, that starts executing right after it is defined, while the second one is executed by jQuery when the document is ready to be manipulated.
To understand better why the first pattern is useful, you can refer to this SO answer.
You also can read more about passing a function to jQuery on the documentation for the .ready()
function.