Call Function on Button Click in Javascript

Last Updated on April 24, 2024 by Roshan Parihar

To call a function on button click in javascript, you can use the onclick attribute and pass the function name as an argument to execute.

There can be many other methods to call a function in javascript. Let’s find out with the examples given below.

How to Call Function on Button Click Using OnClick Attribute in Javascript

You have to first create the function. After that, use the onclick attribute of HTML and pass the function name as its value. Also, don’t forget to add parenthesis () after the function name.

Example 1

Output



When you click the button given above, it executes the code inside the function. You will get an alert message present in the function.

Call Function in Javascript with btn.addEventListener(“click”,FunctionName)

The addEventListener() listens to the event of a mouse. If you want to call a function on button click, you have to first get the element by its id using the document.getElementById() and store it in a variable.

After that, use this variable with the code addEventListener("click",FnName). You have to replace the function name FnName with your created function name.

Example 2

Output



The above example contains the created function with the name FnCall(). When you click the button element given above, it detects the click event calls the function, and executes the code present inside it. You will get an alert message after the execution of the function.

With btn.onclick = FunctionName

In addition to the above methods, you can also use the code btn.onclick = FunctionName. It requires only to change the FunctionName with your created function name. In the code snippet, btn is the variable to which you have to get the button element by its id as given in the example below.

Example 3

Output



The created function contains the alert message. When you click the button given above, you will get an alert message.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.