To automatically call a JavaScript function from an HTML document, you can use the onload
attribute of the body
element to trigger the function when the page finishes loading.
<body onload="myFunction()">
In this example, the onload
attribute is added to the body
element, and its value is set to the name of the function to be called (myFunction
).
You can replace myFunction()
with the name of the function that you want to call. When the body
element loads, the function specified in the onload
attribute will be automatically called.
Automatically call JavaScript function from html example
Simple example code.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script>
function myFunction() {
alert("Hello World!");
}
</script>
</head>
<body onload="myFunction()">
<p>Page loaded.</p>
</body>
</html>
Output:
Here are a few alternatives:
There are other ways to call a JavaScript function automatically from an HTML document.
1. Using the defer
attribute: You can include the defer
attribute on a <script>
tag to defer the execution of the script until the page has finished parsing. This means that any functions defined in the script will be available to call immediately after the page has loaded.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script defer>
function myFunction() {
alert("Hello World!");
}
</script>
</head>
<body>
<h1>Welcome to My Page</h1>
<p>This is an example of calling a JavaScript function automatically using the defer attribute.</p>
<script>
myFunction();
</script>
</body>
</html>
2. Using jQuery’s $(document).ready()
method: If you are using the jQuery library, you can use the $(document).ready()
method to call a function automatically when the document is ready.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
alert("Hello World!");
});
</script>
</head>
<body>
<h1>Welcome to My Page</h1>
<p>This is an example of calling a JavaScript function automatically using jQuery's $(document).ready() method.</p>
</body>
</html>
3. Using the setTimeout()
method: You can also use the setTimeout()
method to delay the execution of a function until a specified amount of time has elapsed.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script>
function myFunction() {
alert("Hello World!");
}
setTimeout(myFunction, 1000);
</script>
</head>
<body>
Comment if you have any doubts or suggestions on this JS HTML code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version