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>
$(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:
See the jQuery documentation for a more thorough explanation