Add a Click event listener to a Button in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 31, 2022

banner

Photo from Unsplash

Add a Click event listener to a Button in TypeScript #

To add a click event listener to a button in TypeScript:

  1. Select the button element.
  2. Use the addEventListener() method to add a click event listener to it.
  3. The method will invoke a function every time the button is clicked.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn">Click</button> <script src="./src/index.ts"></script> </body> </html>

And here is the related TypeScript code.

src/index.ts
const button = document.getElementById('btn'); button?.addEventListener('click', function handleClick(event) { console.log('button clicked'); console.log(event); console.log(event.target); });

We used the document.getElementById method to select the button element.

The getElementById method returns null if no element with the provided id was found in the DOM, so we had to use the optional chaining (?.) operator to short-circuit if the button variable stores a null value.

We called the addEventListener method on the button element.

The addEventListener method takes 2 arguments:

  1. The type of the event to listen for. If you need a list of all of the available event types, check out this MDN events list.

  2. A function to be invoked every time the event is triggered.

The function in the example gets invoked every time the button is clicked and logs a message to the console.

The event parameter is an object containing many different properties. For example, event.target refers to the button that was clicked.

You can use the same approach to add a click event listener to multiple buttons.

src/index.ts
const buttons = Array.from(document.getElementsByClassName('btn')); buttons.forEach(btn => { btn.addEventListener('click', function handleClick(event) { console.log('button clicked'); console.log(event); console.log(event.target); }); });

We used the document.getElementsByClassName method to select a collection of elements with the btn class and converted the collection to an array.

The function we passed to the forEach() method gets called for each element (button) in the array and adds a click event listener to each.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.