Ask the Web Pro 10-Minute Solutions

Build an HTML-Based Color Picker
By Charles C. Caison

Reduce the time it takes to develop your Web pages by building an HTML-based color picker

Many times the systems you build are designed to support or administer/configure other systems. You can use such a system as a set of maintenance Web pages to update the look or content of another Web application after that application has been deployed. For example, you may want to provide a way to easily modify the background color, hyperlink color, or other element's colors for a set of pages. This month's 10-minute solution shows you how to include a script-based color picker in your administration/configuration pages.

I frequently use this color picker to enable administrative users to visually pick a color and save numeric representations of those colors in a database. Typically these color representations will be read back out from the database to Web pages at run time and dynamically included in the definition of page elements. This makes it easy to change the color of virtually any element on a Web page without needing to modify code of the page itself. This 10-minute solution focuses on the color picker itself. The functionality for saving the data to the database is not covered in this article.

The sample page provides a sample color swatch and shows an example of the chosen color. Because of the differences between browsers (Internet Explorer (IE) and Netscape Navigator (NN)), the mechanism for doing so is different depending upon the browser used. As a result, one of the first things you need to do is determine which browser is being used.

You can use a simple function named IsIE() to determine whether or not the browser used is a Windows platform version of IE. If it is, subsequent code will use the features that IE supports, otherwise it will use the features that NN supports. This code should be sufficient to accomplish its purpose as an in-house administration tool because many organizations that have standardized on a particular browser have chosen either IE4+ or NN4+ as their in-house standard browser.

As the page loads, IsIE() will run.


<SCRIPT LANGUAGE="JavaScript">
var usingIE = isIE()

function isIE()
{

	if ((navigator.userAgent.indexOf("IE") == -1) 
	|| (navigator.userAgent.indexOf("Windows") == -1))
	{
		return false;
		
	}
	else
	{
		return true;
	}
	
}

// More script below...

The function will return either true or false and that value will be stored in a variable that is accessible to all other client-side functions on the page. The function uses the "indexOf" function of the intrinsic string object. That function is similar to the VBScript "InStr()" function. In this case, the string is represented by the variable named "userAgent". That variable holds identifying information from the browser itself. All modern browsers provide "userAgent" information, but the exact content is browser-dependent.

Usually "userAgent" contains (among other things) the name of the browser and the platform on which the browser is running. Here, you are searching "userAgent" for the text "IE" and "Windows". If the text is found, the numeric position of the start of that text is returned from the function. If that text is not found -1 is returned from the function. The double pipe (||) is JavaScript's "OR" operator.

As the page loads, you also call a function in the window_onload() event handler function.


function window_onload() {
	CallshowSampleColor();
}

That function will, in turn, call another function in one of two different ways depending upon the browser that is being used.


function CallshowSampleColor()
{
	if (usingIE) 
	{
	        var newColor = 
showSampleColor(SampleCell,document.MyForm.colors);               
	}
	else
	{
		var newColor = 
showSampleColor(document.layers.myLayer, 
document.MyForm.colors) 				
	}
	
	if (newColor != '')
	{
		alert("Now save " + newColor + " to the 
database.");   
	}

} 

In this example, you are using the newColor variable that is returned from the function to display text in an alert() box. In your own code, you would do something more productive with it, like save it to a database or apply the color to a page element.

Notice that the usingIE variable is used to determine which way the other function will be called. If you are using IE, the function will get passed a reference to a table cell on the page. If the browser is not IE, then it will get passed a reference to a <ILAYER> that is on the page. In either case, the function will receive a reference to a listbox named "colors" that is on a page form. This reference will enable you to get the currently selected color.

As the page loads, either the cell named SampleCell (through the <TD></TD> tag pair) or <ILAYER> will get generated and written to the page. Again, the one that happens depends upon the browser that is being used.


<TD>					                        
<SCRIPT language=JavaScript>
if (usingIE)
{
	document.writeln("<SPAN id=MySpan>")
	document.writeln("<TD align=center 
name=SampleCell id=SampleCell>")
	document.writeln("</TD>")
	document.writeln("</SPAN>")
}
else
{
	document.writeln("<ILAYER bgColor='Red' 
name='myLayer' ID='myLayer'>")
	document.writeln(" <strong>Sample</str
ong> ")
	document.writeln("</ILAYER>")
}
</SCRIPT>
</TD>

A <LAYER> is a NN-specific element that simply represents a controllable area on the page. You can control the horizontal and vertical position, background colors, and other attributes of a <LAYER>. The <LAYER> can contain other elements such as textboxes and can be positioned anywhere on the page, even on top of other elements.

The <IFRAME> is an "inline" <LAYER> and is similar in function to the <LAYER>. The difference is that the <IFRAME> appears on the page at whatever position it is in the HTML code. This behavior is similar to the way text is treated on your page. The text appears wherever it is entered in the HTML code, as opposed to specifying the horizontal and vertical positions of where it will appear, as can be done with the <LAYER>. The <ILAYER> in the previous example will get written inside of a table cell and that is where it will appear on the page.

A <SPAN> is used in IE and is a lot like a <LAYER>. It simply defines a controllable area and can contain other elements. If the browser is IE, a <SPAN> will get written to the page. If the browser is NN, a <LAYER> will get written to the page. Both occur using the writeln method of the document object and both browsers support document.writeln. You can use it to write a line of text to the page and append a new line character to the line.

The listbox displays all available colors and defines what should happen when the user chooses a new color. In this case, you will change the color that is displayed in the <SPAN> or the <LAYER>, depending on the browser being used. Here, you call the CallshowSampleColor() function:


<SELECT NAME="colors" onChange="CallshowSampleColor();">
	<OPTION VALUE="" SELECTED>Pick a color!
	<OPTION VALUE=F0F8FF>aliceblue
	etc...
</SELECT>

The function CallshowSampleColor() will call showSampleColor(applyNewColorTo, colorFromListbox). That function will change the sample color shown. The first input argument, "applyNewColorTo", will hold a reference to either the cell in the <SPAN> or to the <LAYER>. In either case, you change the bgColor property to the newly selected color. The variable, "colorFromListbox" contains a reference to the listbox from which the newly selected color is retrieved. The advantage is that you can have several color-picker listboxes on your page and use this function with all of them. Just pass in a different reference for a different listbox.


function showSampleColor(applyNewColorTo, colorFromListbox) 
{       
        var selectedItem = colorFromListbox.selectedIndex;
		var newColor = colorFromListbox.options[selectedItem].value;
        
        applyNewColorTo.bgColor = newColor;
        
		if (usingIE)
		{   
			if (applyNewColorTo.bgColor == "000000" || 
applyNewColorTo.bgColor == "#000000")
			{
			        applyNewColorTo.innerHTML = 
'<b><font 
color=ffffff>Sample</font></b>'
			}
			else
			{
			        applyNewColorTo.innerHTML = 
'<b><font 
color=000000>Sample</font></b>'
			}
		}
        return newColor;    
}

The selectedIndex property tells you the numeric index of the selected listbox item. When you use that with colorFromListbox.options[selectedItem].value, you can retrieve the numeric color of the selected color. The value is defined in the listbox definition with code such as this:


<OPTION VALUE=F0F8FF>aliceblue

In this case, the value of this option is "F0F8FF", which is the hexidecimal value for aliceblue. You would store that hexidecimal value in the database. If you are using NN, then assigning the value of bgColor to the new color value is sufficient. If using IE, you can use the innerHTML property of the <SPAN> to display other stuff.

The innerHTML property of the <SPAN> is an incredibly useful property that enables you to generate any HTML at run time and display the results of that HTML in the <SPAN> immediately. Using innerHTML, you can dynamically create any text, any HTML intrinsic control and many other elements. You can generate and display virtually any HTML at run time. In this case, you are simply adding the word "Sample" and formatting the word.

Using a color picker can go a long way when using HTML-based administrative pages. It makes it extremely easy to apply different colors to multiple page elements without modifying a single line of code. You can easily select and try out different combinations of colors on your pages. This lets you instantly see which ones work together and which ones don't. Consider using a color picker in your applications to reduce the amount of time required to achieve that perfect look.

Click here to see the complete sample page in colors.htm.

 
Other 10-Minute Solutions
 Write Text Files to a Drive on a Web Server
 Create Clickable Image Hotspots
 Programmatically Convert Excel Spreadsheets to HTML
 Detecting Browser Type and Client Settings
 Create a Cool Color-Changing Rollover Effect
 Launch a Window From a Listbox Using JavaScript
 Add User-Interface Elements to Your Web Pages
 Provide Online Help Using Layers in Netscape
 Build an HTML-Based Color Picker
 Manipulate Browser Windows Using JavaScript
 Control Scriptlets With JavaScript
 Extract Data From a Web Site
 Create Lightning-Fast Tabbed Windows in IE
 Add Context-Sensitive Help to Your IE Applications
 Add Dramatic Transition Effects to Your Web Pages
 Create Cross-Browser Scrolling Hyperlinks
 Enable Users to Set Home Pages with a Single Click
 A Painless Introduction to the Wonderful World of XML


Ask the Web Pro | Who is the Pro? | Usage Policies | Search | Feedback


Sponsored Links


Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map
Jupiterweb networks

internet.comearthweb.comDevx.comClickZ

Search Jupiterweb:

Jupitermedia Corporation has four divisions:
JupiterWeb, JupiterResearch, JupiterEvents, and JupiterImages

Copyright 2004 Jupitermedia Corporation All Rights Reserved.
Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Jupitermedia Corporate Info | Newsletters | Tech Jobs | E-mail Offers