Handling JavaScript events on multiple elements
Implementing proper event handling on your site or application is a design issue, meaning there are many ways of solving a problem and choosing the right way is a matter of skill and experience. Today I want to talk about handling events on multiple elements because a great deal of JavaScript developers are constantly struggling to get some overcomplicated code working—usually looping over a set of elements and attaching a handler to each one. When they need to identify which of the targets actually triggered the event, or when they inject new elements as a result of an Ajax request and find out they need to re-apply all the handlers again, they start pulling their hairs out. Let’s look at an approach where we don’t need loops; we’ll simply play with bubbles. Sometimes this is called event delegation.