HTML Event Handling in TypeScript

Aniruddha Chatterjee
Geek Culture
Published in
4 min readJun 15, 2021

TypeScript is a beautiful language and I personally enjoy coding in it as compared to JavaScript. While there are plenty of frontend libraries and frameworks that support TypeScript, I recently tried writing up TypeScript functions with pure HTML codes for a project. One task I had to complete was to write an event handler function for an element. Let us take a look at HTML event handling with TypeScript.

Working with TypeScript

DOM Events are fired to notify code of “interesting changes” that may affect code execution.

Borrowed from MDN Docs, this definition of DOM Events is perhaps the most accurate one. Events are nothing but a way of letting us know that some change has occurred in the DOM. This allows us to make our web pages interactive, make them react to these changes. Let us see how we can act on these changes using the TypeScript programming language.

Prerequisites

This post is written assuming you know how to use the basics of TypeScript. Small explanations as to what our code does are given, but no elaboration is made.

Also, it will be helpful if you have Node.js and TypeScript already installed. You can try the online TypeScript Playground. But executing TypeScript with Node.js is preferred.

You can refer to a previous story First Step towards TypeScript to learn how you can get started with TypeScript.

Creating a Simple Project

Our objective for the day is to learn how event handlers work. Now, to add an event handler, we have two options at hand:

  1. Using addEventListener()
  2. Using specific onevent handlers

This post will be covering the first approach, as I always feel that we should not take up specific things while we are learning something for the first time.

Let us write down a simple code:

This code will:

  1. Fetch an element by the id “sample”
  2. Add an event listener that listens for “click” event
  3. Change the background color of the element to “red”

Let us dive into the code a bit deeper.

Understanding how the code works

If we look up for the function definition of addEventListener, we get

(method) HTMLElement.addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined): void (+1 overload)

We see that the first parameter is type and the second parameter is listener. This listener in turn is a function itself, that accepts a HTMLElement and HTMLElementEventMap as parameters.

So, addEventListener(“click”, listenerFunction) means that we want to listen to the “click” event (a single mouse click) and then execute the listenerFunction whenever a click is encountered. Pretty simple right?

The listenerFunction is a simple function that takes in two parameters, this and ev, having the types of “HTMLElement” and “Event” respectively. Since we are getting a HTMLElement, we can directly work on it to change any property we want (to change the background color in our case).

We are using “preventDefault()” on the event to prevent the default action take as it normally would be. You can read more on it in the “Further Ahead” section.

Executing the code

Let us try and execute our code now.

Step 1: We will use a very simple HTML file for the execution.

We are having a single div element with height and width as 200px and the background color initially set to blue. The element has an id of “sample”, which our script will use to identify the element.

We also have our script imported in the head section since it is a very small script (you should not include too many scripts in the head). And we are executing the initFunction() to attach the event listener to our div element.

Setp 2: But wait? Our file is in TypeScript, but we are importing a JavaScript file? Well, we just need to run the compiler!

npx tsc script.ts

Here, npx ensures that even if TypeScript is not globally installed, we can use tsc to compile our files.

Step 3: Now that everything is ready, all we need is a server. If you are on Windows, you can use IIS. Linux users like me would want to use nginx or apache. But for the sheer simplicity, we are going to use a VS Code extension, Live Server.

Once you have installed the extension, press Alt + L and Alt + O on your keyboard. Your browser should open a page showing a blue box.

Initial state

Click on the blue box, and voila! The box is now red.

After a single mouse button click

Conclusion

That ends our play time with Event Handlers using TypeScript. It is super easy to attach event listeners and work with elements in TypeScript, as long you follow the types of the parameters properly.

You can add any events besides click. You can put any logic in your handler function and it will work like hot butter through knife. You can follow up the links in the “Further Ahead” section to learn more on various topics.

For the time being, adieu!

Further Ahead

--

--

Aniruddha Chatterjee
Geek Culture

Nocturnal animal that thrives on caffeine and loves software development.