JavaScript – Call Function on Button Click
There are two methods to call a function on button click in JavaScript. They are
Method 1: Use addEventListener() Method
- Get the reference to the button. For example, using getElementById() method.
- Call addEventListener() function on the button with the “click” action and function passed as arguments.
As a result, when the button is clicked, the specified function will be called.
index.html
ADVERTISEMENT
Method 2: Use onclick Attribute
- Add onclick attribute to the button in HTML code.
- Assign the function call to the attribute.
Run the following example, and when the button is clicked, the specified function in the onclick
attribute will be called.
index.html
Conclusion
In this JavaScript Tutorial, we learned how to call a function when button is clicked.