How to Create an On-Page Load Event in jQuery

Sheeraz Gul Feb 02, 2024
How to Create an On-Page Load Event in jQuery

The method on() with the load event is used to create an on-page load event in jQuery. This tutorial demonstrates how to create an on-page load event in jQuery.

Create an On-Page Load Event in jQuery

Previously, jQuery had the function load(), which worked as an on-page load or document.ready event, but this method was deprecated in jQuery version 1.8 and removed in version 3.0. Now, the method on() can be used with the load event to perform an operation once the page is fully loaded.

The on() method with the load event works when everything is loaded on the page, including stylesheets, images, videos, etc.

The syntax for the on() method is:

$(window).on('load', functionforOnPageLoad() )

Where the function will be called when the page is fully loaded. Let’s try an example:

<!DOCTYPE html>
<html>

<head>
    <title> jQuery On Page Load </title>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script>
</head>

<body>

    <script type="text/javascript">
        $(window).on('load', AlertMessage());

        function AlertMessage() {
            alert("Hello This is Page is fully loaded");
        }
    </script>
</body>

</html>

The code above will alert the message when the page is fully loaded. See output:

jQuery On Page Load Alert

Let’s try another example to show the current time once the page is fully loaded. See example:

<!DOCTYPE html>
<html>

<head>
    <title> jQuery On Page Load </title>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script>
</head>
<body>

    <p> The current Time is: </p>
    <span class="date"></span>

    <script type="text/javascript">
        $(window).on('load', ShowCurrentTime());

        function ShowCurrentTime() {
            document.querySelector("span").textContent = new Date();
        }
    </script>
</body>
</html>

The code above will show the current time once the page is fully loaded. See output:

jQuery On Page Load

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - jQuery Event