1

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

asked Dec 29, 2013 at 22:28
4
  • Please type the code in the question. Images are not SEO friendly. Commented Dec 29, 2013 at 22:30
  • 2
    Different forms of $(document).ready Commented Dec 29, 2013 at 22:32
  • 2
    Don't understand what you mean. The $(function) is called on dom ready. This is basic jQuery stuff. Commented Dec 29, 2013 at 22:32
  • 1
    The key here is that functions are objects, and as such, they have properties, and can be passed around. Commented Dec 29, 2013 at 22:39

3 Answers 3

2

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

answered Dec 29, 2013 at 22:32
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Dec 29, 2013 at 22:32

Comments

0

writing $(init) is the same as using an anonymous function: $(function(){

Both pass a function into the document ready

answered Dec 29, 2013 at 22:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.