I found myself over the weekend needing to create CSS classes dynamically. Not just add a class to a DOM element, which is easy, but actually building a CSS class based on user input and attaching it to selected elements.
Proved to be harder than it sounds.
var green = {
color: "#00FF00"
};
Object.extend(Element.Methods, {
setClass:function(element, className) {
element = $(element);
element.addClassName(className);
klass = eval(className);
for (var property in klass) {
element.style[property] = klass[property];
}
}
});
Element.addMethods();
function changeClass() {
elements = document.getElementsByClassName("red");
elements.each(function(e) {
e.setClass("green");
});
}
This code lets you specify a “CSS Class” as a Javascript object. Then you can use the Element.setClass to add the properties to the element style. The changeClass() function finds all the “red” elements and sets them to use the “green” Virtual CSS class. I use addClassName to add the new class name, which may cause conflicts with existing CSS classes.
The name is added because I was thinking that I would need a way to remove the class. At the moment I don’t, but it wouldn’t be all that hard to implement. You would store the element’s original properties and remove the class name, and reset all the overridden styles. The disadvantage of what I am doing is overriding the styles at the element level - these will take precedence in CSS.
I am positive there is an easier way of doing this with Prototype and Scriptaculous, so let me know if find one. I looked at interacting with the styles directly using the DOM, but it’s pretty messy.