Categories
JavaScript Answers

How to add HTML button click event handlers with JavaScript?

Spread the love

Sometimes, we want to add HTML button click event handlers with JavaScript.

In this article, we’ll look at how to add HTML button click event handlers with JavaScript.

How to add HTML button click event handlers with JavaScript?

To add HTML button click event handlers with JavaScript, we can call addEventListener on the button.

For instance, we write:

<input type="button" id="myButton" value="Add"/>

to add a button.

Then we write:

const myBtn = document.getElementById('myButton');
myBtn.addEventListener('click', (event) => {
  console.log('clicked')
});

We select the button with document.getElementById.

Then we call addEventListener with 'click' and the click event handler respectively.

Therefore, when we click on the button, we see 'clicked' logged.

Conclusion

To add HTML button click event handlers with JavaScript, we can call addEventListener on the button.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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