September 24, 1999 - Detecting the Number of Colors | WebReference

September 24, 1999 - Detecting the Number of Colors

Yehuda Shiran September 24, 1999
Detecting the Number of Colors
Tips: September 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

The screen object combines several useful properties. You can take advantage of its colorDepth property to find out how may colors are supported. For example, if the user has 256 colors, the value of screen.colorDepth would be 8 (28 = 256).

This property is supported by Navigator 4.0x, Internet Explorer 4.0x, and above. It normally holds one of the following values: 4, 8, 16, 24. The following cross-browser, backward-compatible piece of code shows how you can display an image based on the number of available colors:

<SCRIPT LANGUAGE="JavaScript">
<!--
var bName = navigator.appName;
var bVer = parseInt(navigator.appVersion);
var NS2 = (bName == "Netscape" && bVer == 2);
if (window.screen) {
  var url = (screen.colorDepth >= 16) ? "16bit.gif" : "8bit.gif";
  document.write("<IMG SRC='", url, "' HEIGHT='100' WIDTH='300'>");
} else if (!NS2) {
  document.write("<IMG SRC='8bit.gif' HEIGHT='100' WIDTH='300'>");
}
// -->
</SCRIPT>
<NOSCRIPT>
<IMG SRC="8bit.gif" HEIGHT="100" WIDTH="300">
</NOSCRIPT>

The script may seem a bit complicated, because it accounts for Navigator 2.0x's lack of support for the useful <NOSCRIPT> tag.