Cover Image for How to call a JavaScript Function in Html
89 views

How to call a JavaScript Function in Html

To call a JavaScript function in HTML, you can use the onclick attribute or an event handler. Here are two common ways to call a JavaScript function in HTML:

  1. Using the onclick attribute:
HTML
<button onclick="myFunction()">Click me</button>

In the above example, the onclick attribute is added to a button element. When the button is clicked, the myFunction() JavaScript function will be called.

  1. Using an event handler:
HTML
 <button id="myButton">Click me</button>
 <script>
   document.getElementById("myButton").addEventListener("click", myFunction);
   function myFunction() {
     // JavaScript code
   }
 </script>

In this example, an event listener is added to the button using JavaScript. When the button is clicked, the myFunction() JavaScript function will be called.

You can replace myFunction with the name of your desired JavaScript function. Remember to define the function in your JavaScript code either inline or in a separate script tag.

Note: It’s common practice to place the JavaScript code in the <head> section or just before the closing </body> tag for better organization and to ensure the HTML elements are loaded before executing the JavaScript code.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS