By Simon Willison

Opacity and DHTML

By Simon Willison

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 = "alpha(opacity:"+opacity+")";
// Safari

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


  • mmj

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

  • 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:

  • 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


  • Hakan

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

Get the latest in JavaScript, once a week, for free.