47

I have seen people writing

$(document).ready(function(){
});

and some writing

$(function() {
 });

What's the difference and when to use what?

asked Sep 7, 2009 at 7:39

2 Answers 2

53

$ is the jQuery object itself, which when called implements a whole pile of different interfaces. $('string') runs a selector or constructs a node; $(domElement) wraps an element... and $(a_function) is a convenient short hand for $(document).ready(a_function). See the jQuery API docs for (much) more information.

A note in passing: $(function () { ... }) is shorter, but if you ever want to search for all of your on-ready events, you might be wishing that you had .ready to search for :)

answered Sep 7, 2009 at 7:45
Sign up to request clarification or add additional context in comments.

Comments

15

There is no difference.

One is a convenient shorthand that calls the other internally.

From the jQuery docs:

A shorthand for $(document).ready(). Allows you to bind a function to be executed when the DOM document has finished loading. This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it.

You can have as many $(document).ready events on your page as you like. See ready(Function) for details about the ready event.

answered Sep 7, 2009 at 7:41

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.