I have a few pages on a project that use lots of buttons and event listeners. The developers that worked on this page created a single event listener for every button and every state (click, hover, mouseover, mouseout, etc). This seems to standard development practice.
But, to save 600 lines of code I created only one or two listeners using regular expressions and made up HTML tag attributes. For example, we created a video player interface for JWPlayer which included a play, pause, and stop button.
<span ref="playButton">Play</span> <span ref="pauseButton">Play</span> <span ref="stopButton">Play</span>
Normally most people would create an event listener for each button and their click event. But, by using the regular expression I only need to create on event listener for the page. Once clicked I can check to see what button was pressed and run a method call for that button pressed.
jQuery( "[ref$=Button" ).click(
{
if ( jQuery( this ).attr( "ref" ) === "playButton" ) {
playJWPlayerVideo();
}
else if (jQuery( this ).attr( "ref" ) === "pauseButton" ) {
pauseJWPlayerVideo();
}
else {
stopJWPlayerVideo();
}
}
);
For more than 5 click events you might want to use a switch/case statement to make it run faster and to group similar events together to run the same method.