Initial Visibility Woes

Quick Cookie: How to set the initial visibility state of an element to allow for fade-in animation on page load.

The browsers don’t help here any. While Dojo and other toolkits take much of the pain away from cross-browser incompatibles, there are some fundamental things in play when dealing with opacity that must be taken into consideration.

If you wanted to set an element 50% transparent in a cross-browser way in CSS you’d do something like:

#el { 
	opacity:0.5;
	#filter:alpha(50);
}

And while this works, it doesn’t allow you to animate the opacity for that element in Internet Explorer. It causes a sort of double-filter and has predictable though undesirable results.

You can easily “setup” the element properly to allow for opacity animations by using dojo.style on a “plain” node (with no opacity: or filer: CSS rules):

dojo.style("el", "opacity", 0);

But in order to do that, we must wait until the DOM is ready:

dojo.addOnLoad(function(){
	dojo.style("el", "opacity", 0);
});

Unfortunately, after the DOM is ready, the element is visible to our user then immediately goes to 0% opacity. We could set display:none in CSS, but that is slightly different as our element will have no dimensions and take up no space in the layout.

A quick and dirty solution I use from time to time to work around this browser quirk involves setting the initial state in pure CSS with visibility:hidden (by way of a special .className), and registering an addOnLoad function to fix those nodes with proper opacities.

Start with a plain CSS class unique to the nodes we want to add this behavior to. I use startsHidden:

.startsHidden {
	visibility:hidden;
}

No, when our page starts, all nodes with this class will be in a sort of “simulated” opacity:0 mode. Now we can use dojo.query and that class to find and adjust all our nodes very easily:

dojo.addOnLoad(function(){
	dojo.query(".startsHidden")
		.style("opacity", 0)
		.removeClass("startsHidden")
	;
})

At this point, we can easily (and safely) fade in any of those nodes at any time and not have to concern ourselves with the complexities and nuances of IE’s filter: rules.

Tags: ,