Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery document ready handler

Tags:

jquery

Is there any difference between using:

$(document).ready(function(){

vs.

$(function(){

Does one of these work better than the other in some way, or is the first just a shorthand version of the first?

like image 720
coffeemonitor Avatar asked Apr 28 '10 17:04

coffeemonitor


People also ask

What is the purpose of jQuery document ready () handler?

jQuery ready() Method The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above. The ready() method specifies what happens when a ready event occurs.

What is $( document ready ()?

The jQuery document ready ( $(document). ready() ) method was implemented to execute code when the DOM is fully loaded. Since it executes the given function when all DOM elements are available, you can be sure that trying to access or manipulate elements will work.

How can write document ready function in jQuery?

$( document ).ready() Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).ready() block. console.log( "ready!" );

Where do I put document ready in jQuery?

ready() method will only run after the DOM has loaded. So you'll only see "Hello World!" in the console after the $(document). ready() method has started running. In summary, you can write all your jQuery code inside the $(document).


2 Answers

The latter is the short version of ready handler.

The:

$(function(){

})

is short version of this:

$(document).ready(function(){

}

Both do the same and one task.

jQuery is doing to a good deal with its slogan:

'Code less, do more'

like image 81
Sarfraz Avatar answered Oct 31 '22 00:10

Sarfraz


From the docs:

All three of the following syntaxes are equivalent:

* $(document).ready(handler)
* $().ready(handler) (this is not recommended)
* $(handler)

There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed.

The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

HTH

like image 34
DannyLane Avatar answered Oct 31 '22 00:10

DannyLane