views:

42

answers:

3

Im browsing the flot examples here http://people.iola.dk/olau/flot/examples/turning-series.html

(view source once there)

I came across this :

<script id="source" language="javascript" type="text/javascript">
$(function () {
    var datasets = {
        "usa": {...

The $(function() part. I get that its an anonymous function, I dont get why it is used here. Wouldnt this be just as good :

<script id="source" language="javascript" type="text/javascript">
    var datasets = {
        "usa": {...

I checked over at the jQuery docs (http://api.jquery.com/) and found no special use for function()

+3  A: 
$(function () {

Is for executing the code when the DOM is ready, it's a document.ready handler in jQuery, the same effect as:

$(document).ready(function () {

You want to run certain things on document.ready so that the elements are there, for example if you're using $(".class") as a selector, you wouldn't want that code to run until the DOM was fully loaded, so the elements you're looking for are there, ready to be found by the selector...this means your code would always work, even if it's in the <head>.

For documentation, look at jQuery(callback) in the API.

Nick Craver
+2  A: 

This is shorthand for $(document).ready(handler) which waits until the DOM is fully loaded before running the anonymous function.

Mark E
+1  A: 

In jQuery, $(function() { is shorthand for $(document).ready(function() {.

Yes, your 2nd part would work equally well, but the first one guarantees that the entire DOM for the page is loaded before it is executed.

CMerat