Askable
Askable

Reputation: 255

why define function inside $()?

I came across a public JavaScript fragment that has the following lines of code:

$(function() {
    var v1, v2;
    v1 = new V1;
    return v2 = new V2(v1);
});

The guts of the function are perfectly grokkable. But what is the significance of wrapping this in a $()?

Upvotes: 1

Views: 109

Answers (4)

BrunoLM
BrunoLM

Reputation: 100321

$( fn ) is a shortcut for $(document).ready( fn ), which executes fn when the DOMContent is loaded.

In .ready docs you can see that these 3 are equivalent

$(document).ready(handler)
$().ready(handler) // this one is not recommended
$(handler)

With pure Javascript you could achieve the same behavior using

document.addEventListener("DOMContentLoaded", fn, false);

jQuery docs:

An example on jsFiddle

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

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

This means code inside will be executed as soon as DOM is ready. BTW its jquery syntax, there is no really pure javascript equivalent. It is not equivalent to window.onload = function(){...} which in jquery would be wrote: $(window).load(function(){...}); .

Don't be fooled by auto called anonymous function used in javascript:

(function(){...})()

or (function(){...}())

Upvotes: 4

Misa Lazovic
Misa Lazovic

Reputation: 2823

That notation is alias for $(document).ready(function() { ... });

Upvotes: 0

Jacob
Jacob

Reputation: 78850

$(fn) is a shortcut for $(document).ready(fn).

Upvotes: 8

Related Questions