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
1 2 3 4 5 6 |
<script> function FnCallAt(){ alert("Function call using onclick attribute."); } </script> <button onclick="FnCallAt()">Call Function</button> |
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
1 2 3 4 5 6 7 8 |
<button id="fncallbtn">Call Function</button> <script> function FnCall(){ alert("Function call with click addEventListener."); } var mybtn = document.getElementById("fncallbtn"); mybtn.addEventListener("click",FnCall); </script> |
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
1 2 3 4 5 6 7 |
<button id="fncallClbtn">Call Function</button> <script> function FnCallCl(){ alert("Function call onclick in javascript."); } document.getElementById("fncallClbtn").onclick = FnCallCl; </script> |
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