Stealing jQuery patterns from Bootstrap 10/28/13
Before using Bootstrap I used to bind all of my jQuery event handlers to classes or ID’s like this:
Now I follow Bootstrap’s lead and bind to data attributes. This has a couple of big advantages. First, it’s more modular because it keeps your CSS classes and styles separate from your Javascript functionality. Second, it lets you supply an argument, like a target selector, that can help you avoid hardcoding data into your scripts.
For example, I use this fade toggle click handler1 in a lot of my projects:
With this pattern I can add more fade toggles without touching a line of Javascript, and as Jeff Atwood says, “the best code is no code at all”.
-
I’ve updated this post to use
.on('click',...)
instead of.click
after Scott Williams helpfully pointed out that it was a bit quicker. ↩