jQuery document ready With Examples

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.

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.

By admin

Leave a Reply