Dojo’s got style …

There’s a great little utility function in Dojo Core I use _everywhere_ that goes by the name It isn’t anything new to Dojo (or any JavaScript library for that matter) but in 1.1 it became exceptionally more useful and I’d like to take a second to delve into some of the innards and new features.

To summarize: Dojo style acts as a setter or a getter for a named style property.
You pass it a node and a style, it returns the value. Pass a value as the third argument and the property will be set.

    var node = dojo.byId("foo");
	// set:,"lineHeight","13pt");
	// get:
	var info =,"lineHeight");

If you are accessing a node by it’s id attribute, you can skip the dojo.byId(”foo”) in a pinch.
If the first argument passed to style() is a string, it makes a pass through dojo.byId anyway:"foo","visibility","hidden");

It is a really convenient way to style a property. Assigning the domNode to a variable allows us to reuse the pointer as well as enables your code for better ShrinkSafe compression. (ShrinkSafe replaces variables it knows to be private)

    var node = dojo.byId("foo");,"fontSize","15pt");,"letterSpacing","1em");,"opacity","0.25");

All occurances of “node” in the above example would be replaced with some obfuscated two-character name after the build runs.

New in 1.1 is something that allows us to take that a step further: Object-setter-mode. If the second parameter passed to style is an object, style calls itself for each of the propeties in the object.
This is really nice. We can rewrite the above block as:"foo",{

Now we’re no longer duplicating text and our code is in no way obfuscated during development.
The above shorthand is a much cleaner and safer varition of something you see in JavaScript frequently:

// i'd rather you didn't do this
var node = dojo.byId("foo");
	fontSize = "15pt";
	letterSpacing = "1em";

… which of course will break Internet Explorer, as they use filter: for transparency. normalizes opacity control, and is a reliable way to modify transparency cross-browser.

Another quirky instance where the style name is not normalized: float. Some browsers use cssFloat, others styleFloat. As of 1.1 allows you to use any of of “float”,”cssFloat”, or “styleFloat” when styling the float: property.
(No browser uses “float”, being a reserved JavaScript word. You can’t use it unquoted as an object key, either)"foo","styleFloat","left");"bar","cssFloat","right");"baz",{

Each of the above examples will apply the appropriate float property in a cross-browser way. Neat.

And no cookie would be complete without mentioning the magic of dojo.query … All the signatures above work with — less the node param.


Which will match all div’s class=”link”, and set the background and cursor styles in one fell swoop. Now you know all there is to know about

Tags: ,