I'm trying to understand some JavaScript/jQuery code I downloaded:
<script type="text/javascript">
var messageDelay = 2000; // How long to display status messages (in milliseconds)
// Init the form once the document is ready
$( init );
// Initialize the form
function init() {
$('#contactForm').hide() // Hide the form initially
.submit( submitForm ) // on submit run submitForm() to check the inputs
.addClass( 'positioned' ); // position the form so it sits in the centre of the browser window.
// do more stuff
}
</script>
The $( init ); line is the problem. It seems to be referring to the init() function defined starting farther below, but how does it call init()? The comment line before this says we're calling init() when the DOM is ready, but there's no standard "$(function() {" to wait for the DOM.
Does anyone understand what's going on here?
Thanks
-
Please type the code in the question. Images are not SEO friendly.elclanrs– elclanrs2013年12月29日 22:30:24 +00:00Commented Dec 29, 2013 at 22:30
-
2Different forms of $(document).readyAndreas– Andreas2013年12月29日 22:32:01 +00:00Commented Dec 29, 2013 at 22:32
-
2Don't understand what you mean. The $(function) is called on dom ready. This is basic jQuery stuff.HaukurHaf– HaukurHaf2013年12月29日 22:32:32 +00:00Commented Dec 29, 2013 at 22:32
-
1The key here is that functions are objects, and as such, they have properties, and can be passed around.elclanrs– elclanrs2013年12月29日 22:39:57 +00:00Commented Dec 29, 2013 at 22:39
3 Answers 3
It is the same as writing:
$(function(){
init();
});
Or
$(document).ready(function(){
init();
});
Instead of using anonymous function they are simply passing function name to call ....short answer init() won't fire until jQuery ready event does
Comments
If you pass a function as in $(init), then that's the same as saying you want that function to be called when the document is ready. It's a shorthand notation for:
$(document).ready(init);
Relevant jQuery doc here that shows this form: http://api.jquery.com/jQuery/#jQuery3
I personally find that $(document).ready(init); makes more for more readable code so that's what I use.
Comments
writing $(init) is the same as using an anonymous function: $(function(){
Both pass a function into the document ready