jQuery Document Ready Event

In this article, we will discuss about jQuery document ready event, its syntax and also see some examples of using it.
 

jQuery Document Ready Event

 

The jQuery document ready event is used to prevent jQuery code from running before the document is loaded in the client web browser.

For example, this prevents trying to hide an element that is not created yet, or trying to get size of a file that isn’t completely loaded yet etc.

The document ready event is important as it provides a timeline for the actions to be executed once the document is loaded completely.

 

Syntax of document ready event

 
Here is the syntax :


    $(document).ready(function(){
        //jQuery code here
    });

 

Shorthand method for $(document).ready()

 
Here is a shortcut for document ready method :


    $(function(){
        //jQuery code here
    });

 

Named reference to method in $(document).ready()

 
We can also provided named reference to a method(within reach of ready()) as follows :


function hello(){
  alert("Hello");
}

$(document).ready(hello);

 

Example of using $(document).ready

 

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(this).hide();
    });
});
</script>
</head>
<body>
<button>hide me</button>
</body>
</html>

Result

jquery hide button

Try yourself in JSFiddle here

 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags