Tips for how to decouple your HTML, CSS, and JavaScript
philipwalton.com
philipwalton.com
It's 2013, people that write blogposts should be directing their readers (imo) to using the (html5) data-* attributes (which works equally simple) and actually removes the declaration and mixture of behavior and styling from your css.
For instance your button example:
<button data-behavior='addtocart' data-somespecialparameter='iamspecial' class="add-item">Add to Cart</button>
Would behave on some javascript:jQuery:
$(document.body).on('click' 'button[data-behavior="addtocart"]', myHandlerFunction);
MooTools document.body.addEvent('click:relay(button[data-behavior="addtocart"])', myHandlerFunction);
Handler: function myHandlerFunction(ev) {
console.log("I just got clicked. ", this.getAttribute('data-somespecialparameter'), this);
}
Also, using observers on a container element makes sure that you can dynamically add and remove html elements without having to worry about cleaning up the even handlers. (binding it all on document.body or the nearest container can be debatable for speed reasons, but this is up to you)I should note, though, that if performance is a concern, traversing the DOM for classes is significantly faster than for attributes. Here’s a jsperf example I put together a while back comparing the two: http://jsperf.com/class-vs-data-attribute-selector-performan...
Lastly, it's worth pointing out that it is still possible to style elements with attributes in CSS, so the data-* attribute approach doesn't actually prevent coupling between style and behavior, it's just another convention (like js-* prefixed classes). In both cases it's still up to you to enforce the convention.