Fun with jQuery click events

The Event

 So today at work I was creating a new resource page and while I was assigning click events to some button with jQuery I had a little thought. “Could I do this a better way?”  Let me explain.

Say I have a button and I wanted to add a click event listener. I would probably do it this way. Well honestly I wouldn’t make it an anonymous function, but I’m being lazy here!

So that would work fine and dandy, but what if I had 3 buttons. Do I do the above three times? On the page I was working on today I had three such buttons in a row. A “Cancel”,”Back”, and “Forward”. All of those 3 sat in a div and were more or less happy with their existence as a trio of buttons. Though I should mention that “Back” always wanted to be an “OK”, but he settled. Kind of a sad story. Anyhow, it was here were I began to think that I could be doing this a different way. Why not put a listener on the div element that surrounded the buttons? The click function could simple read the target and then act appropriately. So I gave it a whirl!

And how about that it worked just like I’d expected. So what did I gain by doing this?

  • A single event binding instead of 3
  • A single location where the button clicks funnel too. 
  • A happy set of buttons.

OK that 3rd one isn’t true, well it maybe, who am I to say. So what’s the downside? Well, since all of the clicks now go to a single function, that function has to decide what to do for every element. In the above for example, I might have a switch that reads the targets id and does stuff. Now depending on how many things your event listener is covering… you can see were this is going. Hurrah for pros and cons! 

There you have it, another tool.

Thanks for reading!

Oh, here’s a fiddle to show and tell

Facebooktwittergoogle_plusredditpinterestlinkedinby feather