Return to Snippet

Revision: 11624
at February 11, 2009 16:17 by johnloy


Initial Code
/* State Scope JS. Usage description at http://www.sitepoint.com/article/image-replacement-state-scope/ */

/* Minified */
(function(){d=document;e=d.documentElement;c="images-on";i=new Image();t=i.style;s=d.enableStateScope=function(s,o){if(o)e.className+=" "+s;else e.className=e.className.replace(new RegExp("\\b"+s+"\\b"),"");};if(t.MozBinding!=null){t.backgroundImage="url("+d.location.protocol+"//0)";b=window.getComputedStyle(i,'').backgroundImage;if(b!="none"&&b!="url(invalid-url:)"||d.URL.substr(0,2)=="fi")s(c,true);}else{t.cssText="-webkit-opacity:0";if(t.webkitOpacity==0){i.onload=function(){s(c,i.width>0);};i.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";}else{i.onerror=function(){s(c,true);};i.src="about:blank";}}})();

/* Full */
// Don't copy and paste this code, use the minified script
document.enableStateScope = function(scope, on)
{
  var de = document.documentElement;
  if (on)
	de.className += " " + scope;
  else
	de.className = de.className.replace(
	  new RegExp("\\b" + scope + "\\b"), "");
};

(function()
{
	var de = document.documentElement;
	var img = new Image();
	
	// Handling for Gecko browsers
	if (img.style.MozBinding != null)
	{
		img.style.backgroundImage = "url(" + document.location.protocol + "//0)";
		var bg = window.getComputedStyle(img, '').backgroundImage;
		
		// When images are off, Firefox 2 and lower reports "none"
		// Firefox 3 and higher reports "url(invalid-url:)"
		// Also, always show images for local files in Firefox
		if (bg != "none" && bg != "url(invalid-url:)" || document.URL.substr(0, 2) == "fi")
		{
			document.enableStateScope("images-on", true);
		}
	}
	else
	{
		// Handling for Safari (including iPhone)
		img.style.cssText = "-webkit-opacity:0";
		if (img.style.webkitOpacity == 0)
		{
			img.onload = function()
			{
				// Only enable the state scope if the width
				// of the image is greater than 0.
				document.enableStateScope("images-on", img.width > 0);
			}
			// Source the image to a 43-byte 1x1 pixel GIF image encoded as a data URI.
			img.src = 
				"data:image/gif;base64," +
				"R0lGODlhAQABAIAAAP///wAAACH5BAE" +
				"AAAAALAAAAAABAAEAAAICRAEAOw==";
		}
		// Handling for everything else
		else
		{
			img.onerror = function(e)
			{
				document.enableStateScope("images-on", true);
			}
			img.src = "about:blank";
		}
	}
} )();

Initial URL


Initial Description


Initial Title
State Scope switching Javascript

Initial Tags
css, javascript, textmate

Initial Language
Other