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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<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.