How to call JavaScript function in HTML without onclick

This step-by-step guide helps you understand how to call JavaScript functions in HTML without explicitly using the onclick, providing an alternative way to execute JavaScript based on various events occurring on the webpage.

Step 1: Create a JavaScript Function

Create a simple JavaScript function in a <script> tag or an external JavaScript file.

<script> 
  function greet() 
  { 
    alert('Hello, World!'); 
  } 
</script> 

In this example, the greet() function displays an alert with the message "Hello, World!".

Step 2: Call the JavaScript Function from HTML

To call the JavaScript function without using onclick, you can use various HTML events such as onload, onmouseover, etc. In this example, we will use the onload event.

<body onload="greet()"> 

<!-- Your HTML content here --> 

</body> 

The onload event triggers the greet() function when the webpage finishes loading.

Complete Example:

Putting it all together.

<html> 
  <head> 
  <title>Call JavaScript Function in HTML Without onclick</title> 
  <script> 
    function greet() { 
      alert('Hello, World!'); 
    } 
  </script> 
</head> 

  <body onload="greet()"> 
   <h1>Welcome</h1> 
   <p>The JavaScript function will be called when the page loads.</p> 
  </body> 
</html> 

Recap:

  • Create a JavaScript function using <script> tags or an external JavaScript file.
  • Use an HTML event (such as onload, onmouseover, etc.) to trigger the JavaScript function without using onclick.
  • In this example, the onload event calls the function when the webpage finishes loading.