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

  1. Get the reference to the button. For example, using getElementById() method.
  2. 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

  1. Add onclick attribute to the button in HTML code.
  2. 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.