2

So I see this code in jquery-ui docs and I wonder why all the statements are wrapped in $(function() {...});

The jquery docs says that $() enhance the object in it, but I fail to see why we need it here. Is it a convention or is it actually meaningful?

<script>
$(function() {
    $( "#draggable" ).draggable();
    $( "#droppable" ).droppable({
        drop: function( event, ui ) {
            $( this )
                .addClass( "ui-state-highlight" )
                .find( "p" )
                    .html( "Dropped!" );
        }
    });
});
</script>
r0dney
  • 735
  • 2
  • 5
  • 16
  • Not exactly a duplicate, but answers the question perfectly: http://stackoverflow.com/questions/1388043/different-forms-of-document-ready – freakish Aug 02 '12 at 14:55

3 Answers3

5

$(function() {}); is, for all intents and purposes, the same as $(document).ready(function() {});; although I believe it is called slightly before document ready.

What it does is call the code within the function when the document has finished being created. That is all the DOM tree will have been created by the time that function loads. This allows you to manipulate the DOM safe in the knowledge those objects will have been created at that time.

Here is an example:

<script>
//This code is called straight away, your DOM hierarchy may not
//be complete and the object #draggable may not have been created yet,
//as such draggable() may not work properly.
$( "#draggable" ).draggable();

//This code is called once the DOM tree is complete,
//as such you know all your objects have been created
$(function() {
    $( "#draggable" ).draggable();
    $( "#droppable" ).droppable({
        drop: function( event, ui ) {
            $( this )
                .addClass( "ui-state-highlight" )
                .find( "p" )
                    .html( "Dropped!" );
        }
    });
});
</script>

See the jQuery documentation for a more thorough explanation

Chris
  • 26,744
  • 48
  • 193
  • 345
3

This is a shorthand for $(document).ready(function() {})

It executes once the whole document is loaded, rather than executing when it's encountered during the parsing.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
2

It also creates a context for the items with-in its' statement block, and this just as important as $(document).ready(function() {}), document ready.

Vinyl Windows
  • 503
  • 1
  • 7
  • 19