It’s possible to call a JavaScript function from HTML without an event trigger. You have to simply define your JavaScript function using the <script>
tag in the <head>
section of your HTML document, and then call it directly from the HTML using the onclick
attribute or any other attribute that can execute JavaScript code.
This allows you to create interactive and dynamic web pages that respond to user input and other events.
HTML call JavaScript function without event example
Simple example code.
First, define your JavaScript function using the <script>
tag in the <head>
section of your HTML document. Then, call the function from your HTML using any attribute that can execute JavaScript code, such as onclick
, onload
, or onsubmit
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
console.log('Hello world!');
}
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
</body>
</html>
Output:
You can also call the function from other parts of the HTML document, such as inside a <div>
or <p>
element, using the same onclick
attribute.
Do comment if you have any doubts or suggestions on this JS HTML topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version