Misuse of the CSS class attribute, or valid design pattern?

By : Ash
Source: Stackoverflow.com

As you most likely already know, it's simple in JQuery to select all elements in the document that have a specific CSS class, and then, using chaining, assign common event handlers to the selected elements:


As usual the class "toolWindow" is also normally defined in CSS and associated with some visual styles:


The class attribute is now responsible for indicating not just the appearance (visual state) of the element, but also the behaviour. As a result, I quite often use this approach and define CSS class names more as pseudo object oriented classes then visual only CSS classes. In other words, each class represents both state (CSS styles) and behaviour (events).

In some cases I have even created classes with no visual styling and simply use them as a convenient way to assign behaviour to elements.

Moreover, the jQuery LiveQuery plugin (and the live() built-in function) make this approach even more effective by automatically binding events to dynamically created elements belonging to a specificed class.

Of late I am primarily using class names as defining a common set of behaviour for associated DOM elements and only later using them to define a visual style.

Questions: Is this a terrible misuse of the CSS "class" attribute, if so why?

On the other hand, perhaps it is a perfectly valid approach to further implementing "separate of concerns" and improving the maintainability of HTML/DHTML pages?

By : Ash


Really, I don't want to rain on this parade, because it seems to be kosher in a de facto way. However, I also see that no one has mentioned http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#class-html at the bottom of which section the W3 recommends against the use of CSS class names to form non-standard micro-syntaxes. I think they're mostly warning us not to make a page that consists entirely of DIV and SPAN elements and uses different classes as custom tags. They don't specifically mention mingling classes with behavior.

By : sqykly

I keep thinking about this. Right now I think multiple classes is still the best approach and as people said, not incorrect. But it makes for a messy DOM if nothing else, when you have a hundred elements like:

<div class="draggable sortable droppable list-item editable text">text</div>

There're some things, like flags, you can assign with the data() method in jQuery. I'd love to see jQuery's data() evolve into a tool like how we're using classes.

By : Corey

This video can help you solving your question :)
By: admin