8

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

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

What i mean is why wrap the function in $

3
  • 1
    different-forms-of-document-ready Commented Feb 21, 2011 at 10:49
  • So the function 'myFunction' will not need to be called? It will run when the document is ready Commented Feb 21, 2011 at 10:56
  • 1
    possible duplicate of Different forms of $(document).ready Commented Aug 16, 2012 at 0:40

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok, i understand the ready, but if a function is declared within ready it will execute without being called?
@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.
3

It's a shortcut for

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

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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.