jQuery Event ready() Method



The jQuery event ready() method is used as a function in jQuery that ensures your code runs only after the Document Object Model (DOM) is fully loaded.

The usage of this method to prevents your JavaScript code from running before rendering the HTML elements on the page, which can cause errors.

Syntax

Following is the syntax of the jQuery event ready() method −

$(selector).ready(function)

Parameters

This method accepts an optional parameter as a function, which is described below −

  • function − An optional function to execute when the DOM is ready.

Return Value

This method does not have any return value.

Example 1

The following is the basic example of the jQuery event ready() method −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
</body>
<script>
    $(document).ready(function(){
       alert("Hi there...!");
    })
</script>
</html>

Output

The above program displays a pop-up alert message −


Example 2

Following is another example of the jQuery event ready() method. We use the slide effect on the paragraph tag, it will only execute once the the entire page is fully loaded −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>To hide or show this message, click on the button below</p>
    <button>Toggle the above element</button>
</body>
<script>
    $(document).ready(function(){
        $('button').click(function(){
            $('p').slideToggle();
        });
    })
</script>
</html>

Output

After executing the above program displays paragraph (p) and button elements. When the button is clicked, the paragraph element will toggle between hiding and showing −


Example 3

The following program changes the background color of the div element, once the entire page is fully loaded −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        color: white;
        width: 200px;
        padding: 10px;
    }
</style>
</head>
<body>
    <div>Tutorialspoint</div>
</body>
<script>
    $(document).ready(function(){
        $('div').css({"background-color": "green"});
    })
</script>
</html>

Output

Once the above program is executed, a div element is displayed with a green background −


jquery_ref_events.htm
Advertisements