1

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 $()?

SunSparc
1,9222 gold badges23 silver badges48 bronze badges
asked May 31, 2013 at 22:54

4 Answers 4

8

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

answered May 31, 2013 at 22:56
Sign up to request clarification or add additional context in comments.

3 Comments

But, nevertheless, defining a function on document ready doesn't make much sense, right? It's just a defintion.
It's a function expression, not just a definition. The code means "use this function, defined here inline, as a handler for the ready event."
Here's a good article on function declarations vs. expressions: javascriptweblog.wordpress.com/2010/07/06/…
4

$(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(){...}())

answered May 31, 2013 at 22:56

2 Comments

It is equivalent to document.addEventListener("DOMContentLoaded", fn, false);
@BrunoLM It's not that simple. Not all browsers support that. But you're right otherwise
1

$( 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

answered May 31, 2013 at 23:44

Comments

0

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

answered May 31, 2013 at 22:59

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.