Better Way to Attach Event Listener with Vanilla JS

Let’s discuss a better way to attach event listeners to a bunch of HTML elements selected by a class name with vanilla JavaScript. With jQuery, this is super easy. You just select the elements by a class name and use .on(). jQuery will handle event listener attachments to multiple elements.

How can we do this with vanilla JS? The first thing comes to my mind is use querySelectorAll() and for..of.. loop to attach event listeners in all the elements. It works. But, it’s not very elegant. Now that the browsers offer better set of APIs, doing this with vanilla JS is as easy as jQuery.

Let’s have a look.

Suppose you have a form with radio button group. By selecting a radio input, you want to trigger an action. In the example below, it has a list of cities and, for the sake of demo, let’s console log the city whenever you pick the radio button.

With jQuery, this is easy.

Now, my first instinct to do this with vanilla JS is to use querySelectorAll() and attach event listener in a for loop.

Hummm… It doesn’t look elegant and for loop is a waste of computation. Can we do this better?

In fact, you can do this better with Element.closest(). The closest() goes up the dom tree and find any parent that matches selector string. Check this out.

This pattern can be used, for example, for a header nav. If you have a multiple elements that you want to trigger events, you can attach event listener once in that header nav div and make closest() do the work instead of creating multiple event listeners.

Yay!

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …