How to Call a JavaScript Function in HTML

To call a JavaScript function from within an HTML document, create a button element with an onclick attribute and set that attribute value to the name of the function to execute.

 

Let's try this with a basic HTML page containing a JavaScript function in the head section of the document and a button that will call the function when clicked.

 

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>

  <script>
    function sendAlert() {
      alert('Hello!');
    }
  </script>

</head>
<body>

  <button type="button" onclick="sendAlert()">Click me</button>

</body>
</html>

 

Call JavaScript in HTML With No User Input

The above example requires a user click to execute the JavaScript function but what about just calling a function from within the HTML? Place the JavaScript function execution statement in an HTML script tag like this:

 

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>

  <script>
   function sendAlert() {
    alert('Hello!');
   }
  </script>

</head>
<body>

<script>sendAlert();</script>

</body>
</html>