Advaith Advaith - 6 months ago 9
jQuery Question

Use of a code in jquery

I have a doubt in jquery

why we use the code

$(document).ready(function() { .... });
?

what is the use of that code in beginning.

what is the difference between

alert (' .... ')


and

$(document).ready(function() {
alert(' ... ')
)};

Answer

When you are working with jQuery, the following usually happens:

  1. You load a static HTML page.
  2. You manipulate that HTML page using js/jQuery.

Usually, you want the static HTML page to finish loading/initialising before you start changing it with jQuery. Wrapping your jQuery in this statement

$(document).ready(function() { .... });

ensures that your jQuery will not execute until the the HTML page says 'I have finished loading'. You can read more here:

https://learn.jquery.com/using-jquery-core/document-ready/

Comments