Javascript – Using CSS classes as decorators – a good pattern

cssdesign-patternsjavascriptjqueryweb-applications

I've been building a web-app with a fairly complex GUI – many small elements alongside eachother and within other elements that need various behaviours (dragging, clicking, but context-sensitive).

My code tends to work like this:

controls start out as html tags

<li>

then I add classes to the tag

<li class = 'static passive included'>

some classes might be for css styling to affect appearance

.static {background: blue; float: left;}

while others are acted upon by jQuery to give behaviour for the associated DOM events

$("#container").delegate(".passive", function {onclick : //do-stuff})

and others might be picked up by normal javascript when scanning the document, eg. collect the text values of all nodes with the 'included' class. So certain DOM elements are GUI objects which implement classes definted through a combination of css and jQuery.

My question is, is this a good way to work? And also are these really 'decorators' – they certainly 'add additional responsibilities to an object dynamcially' but I'm not sure about that term. Finally, do you use this pattern in your own sites?

Best Answer

I think what you're doing is dead on. The benefits of using classes, as opposed to making up attribute names, is that you can still validate the page. No modern browser will get upset about undefined CSS classes, and they are trivial to use with jQuery, et al.