Heapcoding

How to call javascript function on button click in html

Published August 5, 2021

In this tutorial I shall show you how to call javascript function on button click in html.

Step 1 – Create blank html document and write basic html

In the above screenshot you will see I have created a basic html document with basic tags.

Now let’s add a button in our html code.

In the above screenshot you will see I have added a basic html button. Now let’s ad a onclick attribute to call a javaScript function on button click.

In the above screenshot you will see I have added onclick attribute with a value of myFunction().

The value is basically a javascript function. Now lets create this function in javaScript.

In the above screenshot you will see I have created a function with the name “myFunction” and called an alert function inside it to show the message when we click on the button.

So this was the complete process to call a javascript function on button click in html. Let’s test it in our web browser.

In the above screen you can see when I clicked on button an alert popup appeared. It means we have successfully called a javaScript function using html button click.

You may also like: