Facebook Cookbook - Jay Goldman [103]
Be aware that names usually including a hyphen (e.g., text-decoration) need to be spelled out using so-called camel case (i.e., drop the hyphen and capitalize the first letter of the next word):
obj.setStyle('lineHeight', '120%');
If you’re working with an attribute that’s measured in a given unit, note that you have to include the unit in the value:
obj.setStyle('top', '20px');
obj.setStyle('fontSize', '9em');
Be careful with that last one when you’re calculating the value in JavaScript, because it means you need to tack the unit onto the calculated number:
var newWidth = (someValue + someOtherValue) / somethingElse;
obj.setStyle('width', newWidth + 'px');
Note that there is no getter method to complement setStyle(), so you can’t get back an array of style information.
Manipulating CSS Class Names
Problem
I’ve done a great job of setting up my CSS so that I can make things pretty in a very modular and semantically correct fashion while keeping a flawless separation between presentation and content. But how can I apply that CSS programmatically?
Solution
In addition to the nearly standard getClassName() and setClassName() methods, Facebook has added a handful of fantastically useful methods:
obj.addClassName(newClass)
Adds the newClass class name to the object’s className string, checking first to see that it isn’t already there.
obj.removeClassName(oldClass)
Does the exact opposite of addClassName(), but you already knew that.
obj.toggleClassName(someClass)
If obj already has someClass in its className string, the class is removed. Contrary-wise, if it doesn’t already have it, the class is added.
obj.hasClassName(someClass)
If obj has someClass in its className string, returns true. Otherwise, returns false.
NOTE
See Manipulating DOM Elements for an explanation of why you can’t just look at the className property of an object.
Discussion
If you’re not using one of the Ajax-type libraries (which is impossible given the Sandbox renaming), manipulating CSS through JavaScript can be a bag full of pain, crammed with sharp-ended bits of code that do lots of className checking and poke you in the ribs repeatedly. Facebook’s new functions take a whole bunch of those sharp bits and round the corners off, so it’s more like a dull throbbing ache than a real hurty poke. Let’s look an example:
Before you click on the “Ouch!” button, you should see three colored squares and a button, as in Figure 7-1.
Figure 7-1. Before clicking “Ouch!”
When you click on the button (see Figure 7-2), the first div gets the bordered class applied (so it now has a black border), the second div loses the blueDiv class and gains the redDiv one (so it becomes