• Post category:HTML

How to Call JavaScript Function on Button Click in HTML

How to Call JavaScript Function on Button Click in HTML

Learn how to call the button click on the javascript function in HTML with three easy steps.

1. Create a JavaScript Function

We need to create a function using the “function” keyword in javascript. Here I have created a function using a simple alert(). The function we have created here will open the alert box and display the message “Executed successfully”. You can name the function however you like, and in this guide, I call it “sample” as an example.

function sample(){
alert("Executed Successfully")

2. Create a button

We can create a button using the HTML <button> tag. Then inside the button tag, you can name the button however you like, Here I have named the button “Click here”.

3. Link button to Javascipt funtion

We can link the javascript function using “onclick” attribute to <button> tag. If we pass the javascript function name in the “onclick” attribute, the javascript function will be executed when the button is clicked.

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

The final code should look like this:

<!DOCTYPE html>
   <title>Link Button to JS funtion</title>
<button onclick="sample()">Click Here</button>

<script type="text/javascript">
   function sample(){
      alert("Executed Successfully")

See the below image alert box open on the button click

how to call javascript function on button click in html


I hope you find this guide useful and keep learning to code!

Leave a Reply