Dynamically changing the background image applied with the DD_belatedPNG IE6 script

As with most web developers, the usage of PNGs within Internet Explorer 6 has always caused a headache, and whilst there are many JavaScript fixes out there, one of the best so far is DD_belatedPNG by Drew Diller.

Unlike most of the other IE6 PNG fix scripts out there, this one makes use of Microsoft’s implementation of VML instead of Microsoft’s AlphaImageLoader filter, as PNG images show up correctly in a VML fill element.

I have found this to be the best option out there at the moment for getting PNGs to work within IE6.

However, I recently found an issue with it, that granted, not many people will need to do, but I did and I also found a solution for it.

The problem

The issue is simple: I have this existing <div> which on loading the page, has DD_belatedPNG already applied to it. In this case my <div> has a repeating transparent PNG background in green. I wanted to be able to change the className of the <div> on the fly using JavaScript (depending on what content is being loaded, sometimes the background colour changes – currently this is the only difference in the new CSS class definition).

However, when simply calling:

document.getElementById("myDiv").className = "newClassName";

I found that whilst the className had indeed changed, the properties within it have not been applied, which in this case is the new background image, and thus the <div> background remains the same as it was.

The solution

The solution itself is actually quite simple, and there are two quick steps, one of which is a quick change to the DD_belatedPNG script itself.

First of all, as well as applying the new className for the <div>, the background image must also be explicitly set, with its full path:

var baseUrl = location.href.substring(0, location.href.lastIndexOf('/'));
var bgImage = "url('" + baseUrl + "/images/transparent-bg-new.png" + "');
document.getElementById("myDiv").style.backgroundImage = bgImage;

Then, within the DD_belatedPNG code, go to the fixPng function (search for fixPng: function(el)), and where it says:

else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
   return;
}

replace it with:

else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
   if (el.style.backgroundImage.toLowerCase().search('.png') == -1) return;
   else el.currentStyle.backgroundImage = el.style.backgroundImage;
}

For some reason the currentStyle.backgroundImage for this element will be empty, and this enforces the newly assigned style.backgroundImage to be used.

I’ve prepared a test page so you can see it working for yourself. Naturally you need to test it in Internet Explorer 6.

And that’s it really. Hope this has helped you in some way. If so, or you have any questions, or run into issues, please do comment below.