-6

Saw this syntax in a code example:

<script>
  $(function () {
    function fun1(event) {
      ...
    }

    function fun2(event) {
      ...
    }
  });
</script>

Question is what the $(function () {...}) wrapper does here? what's this syntax different from

<script>
  function fun1(event) {
    ...
  }

  function fun2(event) {
    ...
  }
</script>

Thanks

Xin
  • 575
  • 4
  • 20
  • 8
    it's about the first thing they tell you in [the documentation](http://api.jquery.com/ready/) – NDM Aug 05 '13 at 15:51
  • 1
    See also: [What does $(function() {} ); do?](http://stackoverflow.com/q/7642442/1935077) – Petr R. Aug 05 '13 at 15:52
  • I think you didn't word your question and title well. The other important difference between the two snippets you posted is function scope. In the first snippet, since those functions are defined inside an anonymous function, they aren't visible outside the anonymous function. – Jason P Aug 05 '13 at 16:03

4 Answers4

1

$(function(){}) is shorthand for $(document).ready(function(){}). It waits until the DOM is ready before running the passed function.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

$ is an identifier, here it is the jQuery function.

So you call that function with one parameter which is itself a function again (a callback).

When looking up jQuery's documentation, you see that jQuery runs the callback once the DOM structure has been loaded.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
1

Have a look at the docs here In general, it declares these functions at time when DOM loaded. So only declaration time differs. So this construction should be used to define function execution, not declaration.

Yaroslav Yakovlev
  • 6,303
  • 6
  • 39
  • 59
1
$(function() {

});

is equivalent to calling:

$(document).ready(function() {
  // Handler for .ready() called.
});

That means the body of the function will be executed once the DOM is ready.

M. Abbas
  • 6,409
  • 4
  • 33
  • 46