Jomatter

How to Call a Function in JavaScript from HTML?

The direct way to call a JavaScript function from HTML is to attach the function to an HTML event such as onclick.

For example:

<button onclick="showMessage()">Click Me</button>

<script>
  function showMessage() {
    alert("Hello, World!");
  }
</script>

When the user clicks the button, the browser executes showMessage().

JavaScript functions can be called from HTML through event attributes such as onclick, onchange, onsubmit, and onmouseover. For new code, however, addEventListener() is generally preferred because it keeps JavaScript separate from HTML.

1. Call a JavaScript Function with onclick

The simplest syntax is:

<button onclick="functionName()">Click</button>

The function must exist in the JavaScript code:

<script>
  function functionName() {
    console.log("Function called");
  }
</script>

Complete example:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Function Example</title>
</head>
<body>

  <button onclick="greet()">Click Here</button>

  <script>
    function greet() {
      alert("Welcome!");
    }
  </script>

</body>
</html>

The onclick attribute runs when the button receives a click event.

2. Pass Arguments to a JavaScript Function

You can pass values directly from HTML to the function.

<button onclick="greet('John')">Greet</button>

<script>
  function greet(name) {
    alert("Hello " + name);
  }
</script>

Here, clicking the button calls:

greet('John');

You can also pass numbers:

<button onclick="calculate(10, 20)">Calculate</button>

<script>
  function calculate(a, b) {
    alert(a + b);
  }
</script>

The function receives 10 and 20 as its two arguments.

3. Call a Function with the Current Element

Inside an inline event handler, the this keyword refers to the HTML element that triggered the event.

<button onclick="changeText(this)">Click Me</button>

<script>
  function changeText(button) {
    button.textContent = "Clicked";
  }
</script>

The button itself is passed to the changeText() function.

You can also use the event object:

<button onclick="handleClick(event)">Click Me</button>

<script>
  function handleClick(event) {
    console.log(event);
  }
</script>

The event object contains information about the event that occurred.

4. The Preferred Method: addEventListener()

Although onclick works, addEventListener() is usually the better approach for maintainable JavaScript.

HTML:

<button id="myButton">Click Me</button>

JavaScript:

<script>
  function showMessage() {
    alert("Button clicked");
  }

  document
    .getElementById("myButton")
    .addEventListener("click", showMessage);
</script>

This approach keeps the HTML focused on structure and the JavaScript focused on behavior.

You can also use an anonymous function:

document.getElementById("myButton").addEventListener("click", function () {
  alert("Button clicked");
});

Or an arrow function:

document.getElementById("myButton").addEventListener("click", () => {
  alert("Button clicked");
});

5. Calling a Function When a Form Is Submitted

JavaScript functions can also be called from form events.

<form onsubmit="validateForm(event)">
  <input type="text" id="username">
  <button type="submit">Submit</button>
</form>

<script>
  function validateForm(event) {
    event.preventDefault();

    const username = document.getElementById("username").value;

    if (username === "") {
      alert("Username is required");
    }
  }
</script>

The onsubmit attribute calls validateForm() when the form is submitted. Calling event.preventDefault() prevents the browser’s default form submission.

6. Why a Function May Not Work from HTML

A common problem occurs when the function is not available in the global scope.

For example:

<script type="module">
  function greet() {
    alert("Hello");
  }
</script>

<button onclick="greet()">Click</button>

This can fail because functions declared inside a JavaScript module are not automatically properties of the global window object. An inline HTML handler such as onclick="greet()" looks for the function through the page’s available global scope.

With modules, use addEventListener() instead:

<button id="greetButton">Click</button>

<script type="module">
  function greet() {
    alert("Hello");
  }

  document
    .getElementById("greetButton")
    .addEventListener("click", greet);
</script>

This avoids the global-scope problem completely.

7. JavaScript File Instead of an Inline <script>

The JavaScript function can also be stored in an external file.

HTML:

<button id="myButton">Click Me</button>

<script src="script.js"></script>

JavaScript in script.js:

function greet() {
  alert("Hello from JavaScript");
}

document.getElementById("myButton").addEventListener("click", greet);

For a modern application, this separation is generally preferable to writing JavaScript directly inside HTML attributes.

onclick vs. addEventListener()

onclick is valid and useful for simple examples:

<button onclick="greet()">Click</button>

addEventListener() is more flexible:

button.addEventListener("click", greet);

It allows JavaScript to remain separate from HTML, supports multiple listeners for the same event, and works naturally with JavaScript modules.

For a quick HTML example, use onclick. For production code, especially larger applications, use addEventListener().

Conclusion

To call a JavaScript function from HTML, attach the function to an event:

<button onclick="myFunction()">Click</button>

with:

function myFunction() {
  // Code here
}

This is the simplest method. For modern JavaScript development, attach the event in JavaScript instead:

document
  .getElementById("myButton")
  .addEventListener("click", myFunction);

The key distinction is scope: inline handlers such as onclick="myFunction()" require the function to be accessible from the page’s global scope, while addEventListener() works directly with functions declared in normal scripts or JavaScript modules.

You Will Also Like This

How To Create Multiple Web Pages In Html
How To Import An Html File Into Excel
How To Integrate WordPress Blog Into Html Website
How To Link A Css File To An Html File
How To Make More Than One Page In Html
How To Put An Image Beside Text In Html
How To Put Text Under An Image In Html
How To Write A Paragraph In Html
What Is The Purpose Of Html In Web Development