jQuery document ready

Filed Under: jQuery

I am sure you have seen jQuery document ready function many times. $(document).ready() specify the jQuery function to operate after the Document Object Model (DOM) is completely loaded.

jQuery document ready

We must make sure that the web page is ready for manipulation by jQuery methods. That’s why it’s always a best practice to include all your code inside jQuery document ready function block.

jQuery Document Ready Function Syntax

  • $(document).ready( function )
  • $( function )

First we use $(document) to create a jQuery object from  the document. Then .ready() function  is called on that jQuery object, then pass the function we want to execute.

The second syntax $(function) can be used as an alternative to $(document).ready().

This method is not compatible with “onload” attribute. Generally it is not used with <body onload="">. If you want to use the load attribute you can use .load() function in jQuery instead of  .ready() function.

jQuery Document Ready Function Example

Following example demonstrates how to use jQuery document ready function on the web page.

Generally, we include document.ready function after the opening script tag (<script>). 

Button click and the toggle function are inside the document ready block. Therefore, it will not execute before the loading of <button> and <div> elements.


<html>
 <head>
    <title>jQuery Document Ready Function Example</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" language="javascript">

     $(document).ready(function() {

     $("button").click(function () {
     $(".textLine").toggle();
     });

     });
   </script>

  </head>

  <body>

    <button>Click Here to Toggle</button>

     <div class="textLine" style="background-color:yellow;">
      This is a yellow line.....
     </div>
   </body>
</html>

jQuery Document Ready Function Demo

jQuery Document Ready Function Summary

It is always a safer practice to write all your code inside document ready function if you want to make sure that everything is working fine.

That’s all about a quick roundup on document ready function in jQuery.

Comments

  1. Manoj says:

    First Of All Thanks For Posting J query Tutorials In Your Blog Sir. Please Continue This Tutorials With Some Real Time Examples Used In Web Applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages