JavaScript > Events

Onload in JavaScript

How to execute a JavaScript function when html element is loaded in the browser?


In case we want to execute a function when a particular html element is loaded successfully in the page, we can follow this approach.

<body onload="CallFunction()">
    Enter your name:
    <input type="text" name="txtName" id="txtName" />
    <input type="button" id="btn" name="btn" value="Submit" />
    
    <script>
        function CallFunction() {
            document.getElementById("txtName").value = "the page loaded";
        }
    </script>

</body>

In the above code snippet, we have specified onload event in the body element. When the body element of the page loads (body is nothing but the complete page), the CallFunction() executes that writes “the page loaded” text into the textbox.

OUTPUT

 Views: 985 | Post Order: 36



Write for us