O'Reilly logo

Facebook Cookbook by Jay Goldman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required