Manipulating CSS Styles

Problem

I want to make things pretty programmatically.

Solution

Facebook Platform provides a very handy setStyle() method that does exactly what it sounds like it should. The very simplest form lets you set one style attribute at a time:

obj.setStyle('color', 'green');

Basically, pass in an attribute name (e.g., color) and a value (e.g., black). You can also set multiple attributes at the same time:

obj.setStyle({color: 'green', background: 'white'});

Discussion

setStyle() is one of the most useful shortcuts provided by Facebook Platform. If you master it (and the bar is not exactly high on that task), you’ll find dynamic styling a lot like a big slice of tasty chocolate cake. There are only a couple of things you need to look out for:

  • 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 ...

Get Facebook Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.