DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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:

Fail

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.

Code1

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.

Code2

Way 3

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

Code3

Results

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

Results

Conclusion

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)

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post