Skip to main content

Opacity and DHTML

By Simon Willison

JavaScript

Share:

😳 Ever felt a little embarassed sharing your JavaScript? Let's fix it.

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.

New books out now!

💁‍♀️ Fun Fact: Python was ranked #2 on a recent highest paid coders list. *


🤓 Ok. When did a code editor from Microsoft become kinda cool!?