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.

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.

#event-handlers #html #typescript

HTML Event Handling in TypeScript
1.35 GEEK