Q:

Best practices for using CSS classes as a state machine?

I'm working on a CSS3/Javascript UI that is written essentially as a state machine, and the transitions between states (animations) are done entirely in CSS3 animations and transitions.
Right now, to trigger a state change I'm doing something like the following:
function changeState(oldState, newState) {
     element.classList.remove(getCSSClassName(oldState));
     element.classList.add(getCSSClassName(newState));
}

This seems fine for now, and everything seems to work in webkit-based browsers. The rendering of the element doesn't get updated until both of these commands are run (probably nothing until the javascript execution ends). However, I know that some browsers (firefox in particular) layout/rendering changes can occur in the middle of javascript execution.
Is this how I should be doing this? Or is there a better way to trigger a "state change" in terms of swapping CSS classes?

A:

You could use .className and prepare the correct string before you assign it:
function changeState(oldState, newState) {
     var str = element.className;
     str = str.replace(getCSSClassName(oldState),"");
     str = str + getCSSClassName(newState);
     element.className = str;
}

This will make sure that the assignment is done without interrupt. Note that classList isn't supported by IE≤9.

