IE6 PNGs using Javascript

Here’s a very useful PNG hack That I was learning about on Google. There are different ways to achieve transparent PNGs, here is the javascript solution.

Create Javascript File

First You’ll need to create the Javascript file responsible for this hack. This script will need to be included within the head tags of your page.

?View Code JAVASCRIPT
1
2
3
4
5
// PNGHack 1.0.1 (2008-06-18)
// Copyright (c) 2008 Yves Van Goethem and png-hack project contributors
// http://code.google.com/p/png-hack/
// Distributed under MIT X11 License
document.write('<!--[if lte IE 6]><style type="text/css">.hack-png{visibility:hidden}</style><![endif]-->');var PNGHack=function(o){var p='http://pnghack.googlepages.com/spacer.gif';var q=function(f,g,h){if(h.checkIE&&!navigator.userAgent.match(h.checkIE))return;if(!f)f={};var d=f.scope||document;var j=(!f.elm&&g!=2)?d.all:d.getElementsByTagName(f.elm);var k=f.src||'src';var l=new RegExp((f.ext)?'\\w+.'+f.ext.toUpperCase():'\.PNG$');var m=function(a,b){var c=a.style;if(!a.pngsrc)h.elements.push(a);a.pngsrc=a.getAttribute(b);c.width=a.clientWidth;c.height=a.clientHeight;c.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+a.pngsrc+"',sizingMethod='scale')";if(h.remotehost==true)o=p;else if(h.remotehost!=false){var d=function(){a.setAttribute(b,p);};var e=function(){if(a.readyState=='complete'){a.detachEvent('onerror',d);a.detachEvent('onreadystatechange',e);}};a.attachEvent('onerror',d);a.attachEvent('onreadystatechange',e);}a.setAttribute(b,o||'images/spacer.gif');if(a.className.match(/\bhack-png\b/))var x=setTimeout(function(){a.className=a.className.replace(/hack-png/g,'');clearTimeout(x);		},300);};if(g==2){m(f.elm,k);return;}for(var i=0;i<j.length;++i){var n=j[i].getAttribute(k)||'';if(g==0&&j[i].className.match(/\bhack-png\b/)||(g==1&&n.toUpperCase().match(l)))m(j[i],k);}};return{hackClass:function(a){q(a,0,this);},hackExtension:function(a){q(a,1,this);},hackElement:function(a){q(a,2,this);},elements:[],checkIE:'MSIE 5\.5|MSIE 6',remotehost:null};};

Load function

Now you need to load our function between your head tags like this:

?View Code JAVASCRIPT
1
2
3
4
5
6
<script type="text/javascript">
ph = PNGHack('src/spacer.gif');
window.onload = function() {
	ph.hackExtension();
};
</script>

Of course, you’ll need a spacer.gif image.

Add class to image

now add the class to your image, like this:

1
<img src="src/image.png" alt="" class="hack-png" />
 
 
Leave A Reply Here

  Username [*]

  Email Address [*]

  Website

Subscribes to this post comments updates

Please Note: All comments maybe under going moderation so there is no need to resubmit the comments. it will appeared when admin approved it, feel free to subscribes to the post comments rss to stay update