Christian Heilmann

CSS Designer and DOM scripter, sitting in a tree

Monday, February 20th, 2006 at 10:55 pm

Hello, I have a question for the CSS folk out there.

Currently I am writing a book for APress on Practical JavaScript and I am right now at the chapter about JavaScript and CSS working together.

Dynamic classes needed for styling JavaScript effects

The idea is to separate CSS and JavaScript completely – as explained in my Unobtrusive JavaScript Course. The JavaScript will dynamically add and remove classes to style effects instead of keeping the look and feel in JavaScript.

The question I was asking myself now is a maintenance one. I tend to separate out the class names as properties – in case that further down the line you need to use other class names as the initial ones. I also tend to comment the classes. Something like this:


// CSS classes
hideClass:’hide’, // hide elements
currentClass:’current’, // current navigation element
hoverClass:’over’, // hover state

[... lots of dark magic, voodoo and other code…]

Note: If you are confused by the syntax, check the show love to the object literal post.

This does the trick quite nicely for a few CSS classes, but I wondered about sites with several different scripts and sections.

The first set of questions are:

  • Do you feel comfortable with this arrangement?
  • Would you know how to change the CSS class name if necessary?

Now, if there were a lot of dynamic classes to be defined in a site, would you feel more comfortable if all of them were in an own document in JSON, for example named cssclasses.js:

‘hide’:’hide’, // hide elements
‘current’:’current’, // current navigation element
‘hover’:’over’, // hover state
[... and so on for a lot of them…]

As the DOM scripter, this would make it easier to spot what is CSS related, as you’d use css.hide,css.hover and so on.

Another more complex approach would be to use AJAX and parse a CSS file exclusively for dynamic classes (f.e. dynamicstyles.css) – thus leaving the commenting and the syntax to you. The CSS could be something like

/* hide */ .hide{
[... CSS settings …]

/* current */ .current{
[... CSS settings …]

/* warning */ .warning{
[... CSS settings …]

All the DOM scripter would have to provide you with are the comment names.

Defining the scripting enabled and scripting disabled look and feel

I normally tend to apply a single class to the body when JavaScript and the DOM is available. something like:

if(!document.getElementById || !document.createElement){return;}

This allows you to define two states in the CSS for every element:

#nav li{

body.jsenabled #nav li{

Would it be more useful to have two totally separate style sheets, like lowstyles.css and highstyles.css

It would be easy to remove the original styles and replace them with the dynamic ones via the DOM.

Or is all of this overkill? :-)

Share on Mastodon (needs instance)

Share on Twitter

My other work: