Developer Network Home - Help

YUI 2: Color Picker Control

YUI 2: Color Picker Control

The Color Picker Control provides a rich visual interface for color selection. The interaction is a familiar one from the desktop paradigm: Color range and saturation are adjusted via sliders while the technical details of the current color are displayed in RGB, hex, and/or HSV formats.

The Color Picker Control can be used inline or displayed within a popup Dialog; you'll find examples of both of these implementations in the examples section.

Getting Started

To use the Color Picker Control, include the following source files in your web page with the <script> and <link> tags. It is recommended that you use the utilities.js rollup of all the YUI Utilities when using Color Picker. Color Picker's richest user experience requires the Animation Utility, and when used within a Dialog Control the Color Picker commonly uses Connection Manager to save values back to the server. Using utilities.js gives you all the potential power of Color Picker's optional dependencies in addition to its required ones — and all in a single file. (The minimum requirements for Color Picker are Yahoo, Dom, Event, Element, Drag and Drop, and Slider.)

  1. <!-- Dependencies -->
  2. <script src="https://yui-s.yahooapis.com/2.9.0/build/utilities/utilities.js" ></script>
  3. <script src="https://yui-s.yahooapis.com/2.9.0/build/slider/slider-min.js" ></script>
  4.  
  5. <!-- Color Picker source files for CSS and JavaScript -->
  6. <link rel="stylesheet" type="text/css" href="https://yui-s.yahooapis.com/2.9.0/build/colorpicker/assets/skins/sam/colorpicker.css">
  7. <script src="https://yui-s.yahooapis.com/2.9.0/build/colorpicker/colorpicker-min.js" ></script>
  8.  
<!-- Dependencies --> 
<script src="https://yui-s.yahooapis.com/2.9.0/build/utilities/utilities.js" ></script>
<script src="https://yui-s.yahooapis.com/2.9.0/build/slider/slider-min.js" ></script>
 
<!-- Color Picker source files for CSS and JavaScript -->
<link rel="stylesheet" type="text/css" href="https://yui-s.yahooapis.com/2.9.0/build/colorpicker/assets/skins/sam/colorpicker.css">
<script src="https://yui-s.yahooapis.com/2.9.0/build/colorpicker/colorpicker-min.js" ></script>
 
Next, apply the yui-skin-sam class name to an element that is a parent of the element in which the Color Picker Control lives. You can usually accomplish this simply by putting the class on the <body> tag:

  1. <body class="yui-skin-sam">
  2.  
<body class="yui-skin-sam">
 

For more information on skinning YUI components and making use of default skins, see our Understanding YUI Skins article here on the website.

YUI dependency configurator.

YUI Dependency Configurator:

Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.

Note: If you wish to include this component via the YUI Loader, its module name is colorpicker. (Click here for the full list of module names for YUI Loader.)

Where these files come from: The files included using the text above will be served from Yahoo! servers; see "Serving YUI Files from Yahoo!" for important information about this service. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug versions of YUI JavaScript files, please download the library distribution and host the files on your own server.

Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.

Basic Setup: Instantiating a Color Picker via Script

The simplest way to use Color Picker is to create a container element on the page — say, an empty <div> — and let Color Picker automatically create its DOM structure for you on the fly. You might find yourself doing this when you already are providing accessible form fields on the page for color-value entry that don't require a JavaScript-enabled browser; in that case, Color Picker becomes a useful augmentation of the user's experience without closing the door to devices or browsers that don't support JavaScript.

In this simple case, you begin with markup for the containing element:

  1. <div id="container"></div>
  2.  
<div id="container"></div>
 

With your container in place, you can now instantiate your Color Picker and pass into its constructor any special configuration values you wish to use for this instance.

  1. var picker = new YAHOO.widget.ColorPicker("container", {
  2. showhsvcontrols: true,
  3. showhexcontrols: true,
  4. images: {
  5. PICKER_THUMB: "picker_thumb.png",
  6. HUE_THUMB: "hue_thumb.png"
  7. }
  8. });
  9.  
var picker = new YAHOO.widget.ColorPicker("container", {
	showhsvcontrols: true,
	showhexcontrols: true,
	images: {
		PICKER_THUMB: "picker_thumb.png",
		HUE_THUMB: "hue_thumb.png"
	}
});
 

If you are hosting the YUI files on your server, you'll also need to add a bit of CSS for IE6 to allow the transparency in the color gradient mask to apply. The AlphaImageLoader filter's src path needs to be set relative to the page url, not the stylesheet url, as is the norm for other CSS property paths. See the Known Issues section for more detail.

  1. /* Assumes YUI files are installed in the assets/yui
  2.  * subdirectory from the web root */
  3. *html .yui-picker-bg {
  4. background-image: none;
  5. filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/assets/yui/build/colorpicker/assets/picker_mask.png', sizingMethod='scale');
  6. }
/* Assumes YUI files are installed in the assets/yui
 * subdirectory from the web root */
*html .yui-picker-bg {
    background-image: none;
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/assets/yui/build/colorpicker/assets/picker_mask.png', sizingMethod='scale');
}

(Note: As is always the case with Slider Control implementations, you achieve best performance by referencing draggable "thumb" images directly rather than using CSS background images. By default, Color Picker will load these images from Yahoo! servers. As exemplified above, it is easy to customize the location of the thumb images being used.)

With the above script on the page, the Color Picker renders itself immediately and automatically, yielding a visual control that looks like this:

The Color Picker Control

If your containing element (the <div> with the id of container in the above example) is wrapped in a form, all of the form field values that appear as part of the Color Picker's interface will be submitted along with any other form fields contained within the form.

Configuring a Color Picker Control Intance

In the simple example above, three configuration options are shown: showhsvcontrols, showhexcontrols, and images. The second argument of the Color Picker constructor is the right place to specify all your configurations.

Some of the common configuration options include:

Configuration Option Purpose
showcontrols (boolean) Hide/show the entire set of controls. Default: true.
showhexcontrols (boolean) Hide/show the hex controls. Default: true.
showhexsummary (boolean) Hide/show the hex summary. Default: true.
showhsvcontrols (boolean) Hide/show the HSV controls. Default: false.
showrgbcontrols (boolean) Hide/show the RGB controls. Default: true.
showwebsafe (boolean) Hide/show the websafe-color swatch. Default: true.

Refer to the API documentation for all of the configuration options that can be set for a Color Picker instance.

Custom Events in Color Picker

The Color Picker Control exposes one "interesting moment" in its interaction, and that moment is when the Color Picker's color value changes. This event is the rgbChange event, and you subscribe to using the following syntax (assuming you've instantiated Color Picker and assigned it to the variable picker):

  1. //a listener for logging RGB color changes;
  2. //this will only be visible if logger is enabled:
  3. var onRgbChange = function(o) {
  4. /*o is an object
  5. { newValue: (array of R, G, B values),
  6. prevValue: (array of R, G, B values),
  7. type: "rgbChange"
  8. }
  9. */
  10. YAHOO.log("The new color value is " + o.newValue, "info", "example");
  11. }
  12.  
  13. //subscribe to the rgbChange event;
  14. picker.on("rgbChange", onRgbChange);
  15.  
//a listener for logging RGB color changes;
//this will only be visible if logger is enabled:
var onRgbChange = function(o) {
	/*o is an object
		{ newValue: (array of R, G, B values),
		  prevValue: (array of R, G, B values),
		  type: "rgbChange"
		 }
	*/
	YAHOO.log("The new color value is " + o.newValue, "info", "example");
}
 
//subscribe to the rgbChange event;
picker.on("rgbChange", onRgbChange);
 

Note that rgbChange fires any time the user updates the color value by interacting with the Color Picker. The event may also change when a script calls the picker's setValue method; that method will fire rgbChange by default, but you can also call setValue silently and suppress the rgbChange event that would otherwise result.

API Methods in Color Picker

Color Picker offers only one commonly-used API method: setValue. setValue updates the currently displayed color in the picker instance and optionally suppresses the resulting rgbChange event. setValue takes two arguments:

  1. New RGB value: an array containing the new RGB value to which the Color Picker should be set.
  2. Silent flag: if true, the value will be set silently and no rgbChange event will fire.

Here's a simple example of how you might use setValue to reset a Color Picker instance to white, assuming you had instantiated a Color Picker and assigned it to the variable picker:

  1. <button id="reset">Reset Color to White</button>
  2.  
<button id="reset">Reset Color to White</button> 
 
  1. //use setValue to reset the value to white:
  2. YAHOO.util.Event.on("reset", "click", function(e) {
  3. myPicker.setValue([255, 255, 255], false); //false here means that rgbChange
  4. //will fire; true would silence it
  5. });
  6.  
//use setValue to reset the value to white:
YAHOO.util.Event.on("reset", "click", function(e) {
	myPicker.setValue([255, 255, 255], false); //false here means that rgbChange
	                                            //will fire; true would silence it
});
 

setValue is the recommended approach for setting the initial value of your Color Picker instance (that is, you should instantiate your Color Picker and then immediately call setValue to set its initial value.

Customizing Color Picker Element IDs

Color Picker uses a static, predefined set of element IDs for the DOM elements it creates on the page. You can specify new IDs to use for Color Picker by passing a new set of IDs into the constructor.

  1. //These are the default values.
  2. var myPicker = new YAHOO.widget.ColorPicker("yui-picker", {
  3. ids: {
  4. R: "yui-picker-r",
  5. R_HEX: "yui-picker-rhex",
  6. G: "yui-picker-g",
  7. G_HEX: "yui-picker-ghex",
  8. B: "yui-picker-b",
  9. B_HEX: "yui-picker-bhex",
  10. H: "yui-picker-h",
  11. S: "yui-picker-s",
  12. V: "yui-picker-v",
  13. PICKER_BG: "yui-picker-bg",
  14. PICKER_THUMB: "yui-picker-thumb",
  15. HUE_BG: "yui-picker-hue-bg",
  16. HUE_THUMB: "yui-picker-hue-thumb",
  17. HEX: "yui-picker-hex",
  18. SWATCH: "yui-picker-swatch",
  19. WEBSAFE_SWATCH: "yui-picker-websafe-swatch",
  20. CONTROLS: "yui-picker-controls",
  21. RGB_CONTROLS: "yui-picker-rgb-controls",
  22. HSV_CONTROLS: "yui-picker-hsv-controls",
  23. HEX_CONTROLS: "yui-picker-hex-controls",
  24. HEX_SUMMARY: "yui-picker-hex-summary",
  25. CONTROLS_LABEL: "yui-picker-controls-label"
  26. }
  27. });
  28.  
//These are the default values.
var myPicker = new YAHOO.widget.ColorPicker("yui-picker", {
	ids: {
		R:              "yui-picker-r",
		R_HEX:          "yui-picker-rhex",
		G:              "yui-picker-g",
		G_HEX:          "yui-picker-ghex",
		B:              "yui-picker-b",
		B_HEX:          "yui-picker-bhex", 
		H:              "yui-picker-h",
		S:              "yui-picker-s", 
		V:              "yui-picker-v",
		PICKER_BG:      "yui-picker-bg",
		PICKER_THUMB:	"yui-picker-thumb",
		HUE_BG: 		"yui-picker-hue-bg",
		HUE_THUMB:      "yui-picker-hue-thumb", 
		HEX:            "yui-picker-hex",
		SWATCH: 		"yui-picker-swatch",
		WEBSAFE_SWATCH: "yui-picker-websafe-swatch",
		CONTROLS:       "yui-picker-controls",
		RGB_CONTROLS: 	"yui-picker-rgb-controls",
		HSV_CONTROLS: 	"yui-picker-hsv-controls",
		HEX_CONTROLS: 	"yui-picker-hex-controls",
		HEX_SUMMARY: 	"yui-picker-hex-summary",
		CONTROLS_LABEL: "yui-picker-controls-label"	
	}
});
 

Internationalizing the Color Picker UI

Just as you can customize the element ID strings used by Color Picker, you can also customize the text labels used within the interface — whether for purposes of internationalization or simply to give the UI your own flavor. Here's the full constructor configuration syntax populated with the default values for Color Picker's text strings:

  1. //These are the default values.
  2. var myPicker = new YAHOO.widget.ColorPicker("yui-picker", {
  3. txt: {
  4. ILLEGAL_HEX: "Illegal hex value entered",
  5. SHOW_CONTROLS: "Show color details",
  6. HIDE_CONTROLS: "Hide color details",
  7. CURRENT_COLOR: "Currently selected color: {rgb}",
  8. CLOSEST_WEBSAFE:"Closest websafe color: {rgb}. Click to select.",
  9. R: "R",
  10. G: "G",
  11. B: "B",
  12. H: "H",
  13. S: "S",
  14. V: "V",
  15. HEX: "#",
  16. DEG: "\u00B0",
  17. PERCENT: "%"
  18. }
  19. });
  20.  
//These are the default values.
var myPicker = new YAHOO.widget.ColorPicker("yui-picker", {
    txt: {
        ILLEGAL_HEX: 	"Illegal hex value entered",
        SHOW_CONTROLS: 	"Show color details",
        HIDE_CONTROLS: 	"Hide color details",
        CURRENT_COLOR: 	"Currently selected color: {rgb}",
        CLOSEST_WEBSAFE:"Closest websafe color: {rgb}. Click to select.",
        R:              "R", 
        G:              "G",
        B:              "B", 
        H:              "H",
        S:              "S",
        V:              "V",
        HEX:            "#",
        DEG:            "\u00B0",
        PERCENT:        "%"	
    }
});
 

If you are updating the text labels, you are required to supply values for all of the labels. If you are only changing some of the labels, the easiest way to do this is to combine your new values with the default set with YAHOO.lang.merge:

  1. var txt = YAHOO.lang.merge(
  2. YAHOO.widget.ColorPicker.prototype.TXT, {
  3. R: "Red",
  4. G: "Green",
  5. B: "Blue"
  6. });
  7.  
  8. var myPicker = new YAHOO.widget.ColorPicker("yui-picker", {
  9. txt: txt
  10. });
  11.  
var txt = YAHOO.lang.merge(
        YAHOO.widget.ColorPicker.prototype.TXT, {
                R: "Red",
                G: "Green",
                B: "Blue"
        });
 
var myPicker = new YAHOO.widget.ColorPicker("yui-picker", {
    txt: txt
});
 

Making Use of Color Picker's Form Data

Depending on how you configure your Color Picker Control, there are three formats into which color information is encoded:

  1. RGB: In the RGB format, color is described in terms of red, green and blue values, with each value described as an integer between 0 and 255. An RGB value of [0,0,0] is black; a value of [255,255,255] is white.
  2. HSV: HSV is an alternative to RGB in which color is represented in terms of hue, saturation, and value (brightness).
  3. Hexadecimal: The hex value for a color comprises a hexadecimal encoding of the color's RGB value, with each of the three colors represented by its hexadecimal value; this is also known as a "hex triplet" because it runs together the three hex values into a single string. For example, the hex value for 255 is FF; hence, the color white in hexadecimal markup is represented as FFFFFF. In the HTML and CSS standards, we generally prefix hex values with the # sign: #FFFFFF. Hex color descriptions are important because they are the most common way to identify color in HTML and CSS documents.

Color Picker allows you to extract RGB, HSV and hexadecimal values from any color the user has selected. Optionally, you can allow the user to have direct access to RGB, HSV, and hexadecimal values via form fields. When the user updates the form fields, the Color Picker automatically updates to reflect the new value (assuming it is a valid value).

When a form is submitted containing Color Picker data, you will find the following form fields:

Field Name Contents
yui-picker-r Red value for RGB; 0-255.
yui-picker-g Green value for RGB; 0-255.
yui-picker-b Blue value for RGB; 0-255.
yui-picker-h Hue value in HSV space; 0-360.
yui-picker-s Saturation value in HSV space; 0-100 (%).
yui-picker-v Value/brightness value in HSV space; 0-100 (%).
yui-picker-hex Hexadecimal (hex triplet) value for the selected color ; 000000-FFFFFF.

These form fields can be passed to the server via a traditional form post or via Ajax using Connection Manager. We've provided a detailed example of how to make use of Color Picker in a Dialog Control while implementing Connection Manager to transport the data to the server.

Skinning the Color Picker Control

The Color Picker comes with a default presentation or "skin," part of the "Sam Skin" visual treatment that accompanies most YUI controls. You can read more about the general approach to skinning YUI components in this in-depth article.

In the case of the Color Picker Control, there is no "core" CSS treatment — which is to say that there is no CSS that is considered essential to the functioning of the control. All of the CSS provided with Color Picker is part of the Sam Skin visual treatment.

The Color Picker Control

To explore the CSS which controls the Color Picker's presentation, please review the Color Picker Skinning Example wherein the full CSS for the control is displayed.

Known Issues

Gradient doesn't display properly in Internet Explorer 6

capture of gradient mask not showing

ColorPicker uses a transparent png mask to create the gradient effect in the Saturation/Value portion of the ColorPicker. For IE6, this mask is applied using a Microsoft proprietary filter in the included CSS.

  1. /* snip */
  2. *html .yui-picker-bg {
  3. background-image: none;
  4. filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../../build/colorpicker/assets/picker_mask.png', sizingMethod='scale');
  5. }
  6. /* snip */
  7.  
/* snip */
*html .yui-picker-bg {
    background-image: none;
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../../build/colorpicker/assets/picker_mask.png', sizingMethod='scale');
}
/* snip */
 

However, AlphaImageLoader's src is resolved relative to the page, not the CSS file as is typical of CSS url(...) references. This means that the path specified in YUI's sam skin will be incorrect unless your page is located on your server accordingly. If you experience this issue, you can work around it by including the following CSS on your page in a <style> block or in another attached stylesheet:

  1. *html .yui-picker-bg {
  2. filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='PATH/FROM/THIS/PAGE/TO/build/colorpicker/assets/picker_mask.png', sizingMethod='scale');
  3. }
  4.  
*html .yui-picker-bg {
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='PATH/FROM/THIS/PAGE/TO/build/colorpicker/assets/picker_mask.png', sizingMethod='scale');
}
 

Support & Community

The YUI Library and related topics are discussed on the on the YUILibrary.com forums.

Also be sure to check out YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.

Color Picker Control Cheat Sheet:

Cheat Sheet for the Color Picker Control.

Download full set of cheat sheets.

YUI Color Picker Control on del.icio.us:

bookmark on del.icio.us

be the first to bookmark this page!

Copyright © 2016 Yahoo! Inc. All rights reserved.

Privacy Policy - Copyright Policy - Job Openings