JavaScript solution to PNG alpha transparency in IE

Solutions to the problem of PNG alpha transparency in IE6 have been around for a while, as exemplified by this post on Cross-Browser Variable Opacity with PNG on A List Apart. This solution uses script to write in the correct html, or to pass variables to a script and set a property of an object. Other solutions involve using server-side browser sniffing to serve different CSS depending on the browser.

The crux of the problem is that IE6 doesn’t support the Alpha channel of PNG files used as an image. The solution is to take advantage of one of the proprietary DirectX filters built into Internet Explorer (for Windows) and to use this instead of the background image. The important point to note is that it is an ‘either/or’ solution – the PNG is used as a background image for the other browsers, and as a filter source in IE. Including both in IE means the PNG appears but with a nasty grey where all the transparency should be.

I’ve come up with the JavaScript below as an instant fix solution which means no rewriting of existing code is necessary. The CSS file will contain the background image as supported by Firefox and the other (non IE) modern browsers. (IE 7 is supposed to fix this, by the way.) The JavaScript runs through the stylesheet and replaces all of the background images with DirectX filters. The script should be placed in the head of the page just after the stylesheet tags and works automatically (although I haven’t yet tested it in older browsers).

You’ll need to remove some of the linebreaks which I’ve marked with a \n.

if(document.all&&document.styleSheets;)
{
 var stylesheets=document.styleSheets;
 for(var i=0;i0)){
    var imageName=curRule.style.backgroundImage;
    imageName=imageName.substr(4,imageName.\n
length-5);
    curRule.style.backgroundImage='';
    curRule.style.filter="progid:\n
DXImageTransform.Microsoft.AlphaImageLoader\n
(src='"+imageName+"')";
   }
  }
 }
}

The way this works is to loop through each stylesheet, then each rule in the stylesheet, looking for any one with the backgroundImage property set. If it’s set it takes the image name from it (stripping out the url(”) bit) and sets that as the source of a DXImageTransform CSS filter. It then removes the backgroundImage property.

Advertisements
This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s