8

What is the use of writing a jQuery function like so...

$(function myFunction() {
    ...
});

What i mean is why wrap the function in $

Dooie
  • 1,649
  • 7
  • 30
  • 47
  • So the function 'myFunction' will not need to be called? It will run when the document is ready – Dooie Feb 21 '11 at 10:56
  • 1
    possible duplicate of [Different forms of $(document).ready](http://stackoverflow.com/questions/1388043/different-forms-of-document-ready) – kapa Aug 16 '12 at 00:40
  • 1
    [different-forms-of-document-ready](http://stackoverflow.com/questions/1388043/different-forms-of-document-ready) – Stofke Feb 21 '11 at 10:49

3 Answers3

12

I think that you mean like this:

$(function() {
  ...
});

This is shorthand for:

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

What it does is registering a handler for the ready event, so the code in the function will be run as soon as the document has loaded.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • ok, i understand the ready, but if a function is declared within ready it will execute without being called? – Dooie Feb 21 '11 at 10:57
  • 1
    @Dooie: If you use the syntax that you described, it will declare the function with that name, and register the function to handle the event. However, the name of the function is pretty useless, as it's limited to the scope of itself, so it can only be used within the function itself. – Guffa Feb 21 '11 at 11:44
3

It's a shortcut for

$(document).ready(function myFunction() {
    ...
});

See http://api.jquery.com/ready/

Flo
  • 2,738
  • 1
  • 16
  • 12
1

It actually happens to be a short-hand for the following syntax:

function handleDocumentReady ()
{ // handleDocumentReady ()
    // Code to handle initialization goes here...
} // handleDocumentReady ()

$(document).ready (handleDocumentReady);