Better Way to Attach Event Listener with Vanilla JS
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: EventListeners, JavaScript, jQuery, 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!