Opacity and DHTML

Richard Rutter’s Onload image fades without Flash demonstrates a way of creating a “fade-in” effect for a photograph using dynamic alteration of the CSS opacity property. Opacity isn’t part of the CSS 2.1 specification (although it is covered by CSS 3) so different browsers have different ways of controlling it. Richard’s setOpacity() function provides a cross-browser workaround, with code that handles IE, Safari, Konqueror and Gecko-based browsers:


function setOpacity(obj, opacity) {
opacity = (opacity == 100)?99.999:opacity;
// IE/Win
obj.style.filter = "alpha(opacity:"+opacity+")";
// Safari<1.2, Konqueror
obj.style.KHTMLOpacity = opacity/100;
// Older Mozilla and Firefox
obj.style.MozOpacity = opacity/100;
// Safari 1.2, newer Firefox and Mozilla, CSS3
obj.style.opacity = opacity/100;
}

Richard's blog entry provides further background information about the technique.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.sitepoint.com/ mmj

    Whoa! His name is freakishly similar to mine. Thomas Richard Rutter.

  • http://simon.incutio.com/ Skunk

    Heh, and I always assumed that mmj were your initials :)

  • Vinayak

    I have noticed that using text over a half-transparent layer makes the text also transparent. Can this be avoided.

  • Dean Hamack

    This doesn’t work in IE for Mac. I’ve tried using it to create transparent iframes, but to no avail.

  • HardCoded

    I had to comment out the line that sets opacity to 99.999 because in my Firefox 1.0 with monitor set to High Color (16 bit) the colours would stay all wonky. I had to let it go to 100.

    Also, in case you happen to use the script on a dynamic website like I did, you have to test if the image actually exists in the init function, or you get Javascript errors.

    Anyways, working to good effect here:
    http://www.exploregeorgianbay.com

  • http://www.clagnut.com clagnut

    mmj – there’s not too many Rutters around – so it’s always a pleasure to ‘meet’ one of the clan :-)

  • David van Wert

    The only way I’ve found so far around the transparent text issue is to use overlapping divs and z-index– the top div with the text has no background, the bottom div is semi-transparent. This is less than ideal because overlapping the divs necessitates absolute positioning. Nesting the divs (in order to use “relative”) doesn’t work, trying to over-ride the transparency by making the

    100% solid doesn’t do it either… I’ll keep experimenting, but if anybody else has any ideas I’d love to hear ‘em.

  • Bayard Randel

    I

  • Hakan

    I am also suffering for having text transparent with it’s background.. Please send me an email if you could find a solution..
    hakanakkanATgmailDOTcom