What is the use of writing a jQuery function like so...
$(function myFunction() {
...
});
What i mean is why wrap the function in $
asked Feb 21, 2011 at 10:45
Dooie
1,6797 gold badges31 silver badges47 bronze badges
-
1different-forms-of-document-readyStofke– Stofke2011年02月21日 10:49:39 +00:00Commented Feb 21, 2011 at 10:49
-
So the function 'myFunction' will not need to be called? It will run when the document is readyDooie– Dooie2011年02月21日 10:56:13 +00:00Commented Feb 21, 2011 at 10:56
-
1possible duplicate of Different forms of $(document).readykapa– kapa2012年08月16日 00:40:19 +00:00Commented Aug 16, 2012 at 0:40
3 Answers 3
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.
answered Feb 21, 2011 at 10:49
Guffa
703k112 gold badges760 silver badges1k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Dooie
ok, i understand the ready, but if a function is declared within ready it will execute without being called?
Guffa
@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.
It's a shortcut for
$(document).ready(function myFunction() {
...
});
answered Feb 21, 2011 at 10:50
Flo
2,7881 gold badge16 silver badges12 bronze badges
Comments
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
lang-js