Skip to content

Instantly share code, notes, and snippets.

@jonlow
Last active August 29, 2015 14:07
Show Gist options
  • Save jonlow/a6692c500b60c6e0004a to your computer and use it in GitHub Desktop.
Save jonlow/a6692c500b60c6e0004a to your computer and use it in GitHub Desktop.
Fixing IE8 transparent PNG's for inline images that are faded on using jQuery

The Problem

When we use jQuery to fade on images that use an IE8 png fix, there can be issues such as:

  • The PNG fix not working at all, and the image having a black outline or going completely black
  • The png looks ok, but the image doesn't fade on.

##Solution

Wrap the image in a div and apply all styling to the wrapper div. The key is to not target the image with any css, and apply any positioning or class references to the wrapping div.

In the scenario below, we are trying to 'fade on' an image on the page using the .image class

Change

<img class="image" src="img/1.1_img.png" alt="My alt tag" />

to

<div class="image">
  <img src="img/1.1_img.png" alt="My alt tag" />
</div>

Note: The .image class was moved from the image to the wrapping div. Do NOT apply any styling or classes to the image.

####Javascript

Add the below javascript to your project, to apply the png fix to all png images.

var pngFix = function () {
	var i;
	for (i in document.images) {
	    if (document.images[i].src) {
	        var imgSrc = document.images[i].src;
	        if (imgSrc.substr(imgSrc.length-4) === '.png' || imgSrc.substr(imgSrc.length-4) === '.PNG') {
	            document.images[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + imgSrc + "')";
	        }
	    }
	}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment