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

Steve
  • 4,534
  • 9
  • 52
  • 110

3 Answers3

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
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

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

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

Both pass a function into the document ready