How to add event listeners without repeating yourself

One of the key principles of good programming is DRY – Don’t Repeat Yourself!

Here’s one way to reduce repetition with event listeners by using an array .forEach iterator that I’ve used a number of times now. If you haven’t done this before, here you go! If you have an even cleaner and easy to understand solution, please share.

The code below uses jQuery selectors and methods to add ‘mousedown’ event listeners to 4 elements #up, #down, #left and #right.

Code used in an in-class lab to move a ball around the page.