In this tutorial you’ll learn how you can call a JavaScript function on button click in HTML with three easy-to-follow steps.

Step 1: Create a JavaScript function

The first thing to do is create a JavaScript function. In the HTML file, create a JavaScript function and name it whatever you want. Inside the function bracket, add a console log, so you can check whether the JavaScript code is running successfully or not.

In this example, I name the function ‘surprise,’ and inside the console log, I add a text that reads, “Yay, it’s working!”

<script>
  function surprise() {
    console.log("Yay, it's working!");
   }
</script>

Step 2: Create a button

The next step is to create a button that you want to call JavaScript when you click the button.

<button>Click me!</button>

Step 3: Add the onclick attribution

The final step is to add the onclick attribution to the button. This attribution will connect the HTML button to the function, and this is how you will run the JavaScript when you click the button.

<button onclick="surprise()">Click me!</button>

Make sure the value of an onclick attribution matches the name of the function.

Here is how the code should look like at the end:

<button onclick="surprise()">Click me!</button>

<script>
  function surprise() {
    console.log("Yay, it's working!");
  }
</script>

Now you are ready to test it to see if it works. Open the “inspect section” in the browser by right-clicking the mouse and select the Inspect option and click the console tab. When you click the button, you should see the text reading, “Yay, it’s working!”

If it does, then congratulations - you have just learned how to call JavaScript on a button click!

I hope you find this tutorial helpful and happy coding!

Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript