State Scope switching Javascript


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /* State Scope JS. Usage description at http://www.sitepoint.com/article/image-replacement-state-scope/ */
  2.  
  3. /* Minified */
  4. (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";}}})();
  5.  
  6. /* Full */
  7. // Don't copy and paste this code, use the minified script
  8. document.enableStateScope = function(scope, on)
  9. {
  10. var de = document.documentElement;
  11. if (on)
  12. de.className += " " + scope;
  13. else
  14. de.className = de.className.replace(
  15. new RegExp("\\b" + scope + "\\b"), "");
  16. };
  17.  
  18. (function()
  19. {
  20. var de = document.documentElement;
  21. var img = new Image();
  22.  
  23. // Handling for Gecko browsers
  24. if (img.style.MozBinding != null)
  25. {
  26. img.style.backgroundImage = "url(" + document.location.protocol + "//0)";
  27. var bg = window.getComputedStyle(img, '').backgroundImage;
  28.  
  29. // When images are off, Firefox 2 and lower reports "none"
  30. // Firefox 3 and higher reports "url(invalid-url:)"
  31. // Also, always show images for local files in Firefox
  32. if (bg != "none" && bg != "url(invalid-url:)" || document.URL.substr(0, 2) == "fi")
  33. {
  34. document.enableStateScope("images-on", true);
  35. }
  36. }
  37. else
  38. {
  39. // Handling for Safari (including iPhone)
  40. img.style.cssText = "-webkit-opacity:0";
  41. if (img.style.webkitOpacity == 0)
  42. {
  43. img.onload = function()
  44. {
  45. // Only enable the state scope if the width
  46. // of the image is greater than 0.
  47. document.enableStateScope("images-on", img.width > 0);
  48. }
  49. // Source the image to a 43-byte 1x1 pixel GIF image encoded as a data URI.
  50. img.src =
  51. "data:image/gif;base64," +
  52. "R0lGODlhAQABAIAAAP///wAAACH5BAE" +
  53. "AAAAALAAAAAABAAEAAAICRAEAOw==";
  54. }
  55. // Handling for everything else
  56. else
  57. {
  58. img.onerror = function(e)
  59. {
  60. document.enableStateScope("images-on", true);
  61. }
  62. img.src = "about:blank";
  63. }
  64. }
  65. } )();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.