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:
$(".toolWindow").click(toolWindow_click);
$(".toolWindow").keypress(toolWindow_keypress);
As usual the class "toolWindow" is also normally defined in CSS and associated with some visual styles:
.toolWindow{
color:blue;
background-color:white;
}
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?
The "class" is actually part of the document data (and hopefully semantically relevant) not the style or design of it.
This is why it's okay to use for both.
I think it's perfctly valid.
The only rule I try to stick to is that class names should have semantic value. No need for them to have any associated CSS or JavaScript if you don't want too. Just make the class name descriptive of the content.
Bad class names (according to my rule):
<span class="brightRedBold">Wear Protective Gloves</span>
<a class = "openInNewWindow" ...>
To my mind those are just as bad as writing in-line styles and javascript
Good class names:
<span class="urgentWarning">Wear Protective Gloves</span>
<a class = "offSiteLink" ...>
You can attach whatever styles and behaviours you want to those classes and come up with a much more consistent and maintainable design. Try defining a spoken style for "brightRed" for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With