Opacity

-related CSS definitions are the bane of validating, standards-compliant AJAX components no longer. No more must we shout, "Impossible!" and run from the room when a client wants a cool AJAX component for their standards-compliant site.

Let's take a look at how to save both our fancy opacity effects and our valid CSS using some handy DOM scripting.

[This example illustrates a technique described in this blog post.]

In actu

Here it is. You can click the box to download the example (12kb).

Give me valid opacity or give me death!

HTML

<a href="http://www.designlessbetter.com/" id="innerbox">Give me valid opacity or give me death!</a>

CSS

a#transparent
{
	display: block;
	width: 450px;
	padding: 10px;
	height: 180px;
	color: white;
	background-color: black;
	border: 5px #ccc solid;
	text-decoration: none;
	font-family: Helvetica, Arial;
	font-size: 3em;
}

Javascript

(PS. This uses Mootools selectors. You can also use Prototype or Scriptaculous or even old-fashioned document.getElementByIds).

function applyOpacity()
{
    if ($('transparent'))
	    {
        $('transparent').setStyle("filter:","alpha(opacity=20)");
        $('transparent').setStyle("-moz-opacity","0.2");
        $('transparent').setStyle("-khtml-opacity", "0.2");
        $('transparent').setStyle("opacity", "0.2");
        $('transparent').addEvent('mouseover', function(e) {

            $('transparent').setStyle("filter:","alpha(opacity=100)");
            $('transparent').setStyle("-moz-opacity","1.0");
            $('transparent').setStyle("-khtml-opacity", "1.0");
            $('transparent').setStyle("opacity", "1.0");
        });
	        $('transparent').addEvent('mouseout', function(e) {
            $('transparent').setStyle("filter:","alpha(opacity=20)");
            $('transparent').setStyle("-moz-opacity","0.2");
	        $('transparent').setStyle("-khtml-opacity", "0.2");
            $('transparent').setStyle("opacity", "0.2");
        });
    }
}

Yours to take

Here's a working example (12kb), all packaged up and ready to go. Hope this helps.

Valid CSS!