DEV Community

Fernando Guisbert Segales
Fernando Guisbert Segales

Posted on

Multiple Events to a Listener with JavaScript

When we code we usually have one event for one listener but there are cases where we need to add more that one event for the same listener.

Wrong way

The first thing that can come to our mind can be the next code:


But It’s not possible to add two different events for one listener like we did above, so we have different ways to achieve our goal and I will show you 3 ways to do it.

Way 1

We can create 2 events listeners each one for the button element.


Way 2

We can create a variable “myEvents” to store the event listeners and split them and finally loop with a forEach and assign each event listener.


Way 3

We can store our event listeners into an array and loop with a forEach and assign each event listener.



You can watch the results of the code we have seen above in the next image. If you want to test it you can download the code which is store in Github in the next link as a little project:

Link Github Project



The “Way 3” is the best option so far if we want to add multiple events to a listener this way you can avoid rewrite the same code over and over again and remember “Don’t Repeat Yourself”.

Top comments (0)