How to Create a Color Picker in JavaScript | 4
.
How to Create a Color Picker in JavaScript
Creating the Full Color Picker
Creating the full color picker starts with creating the DIV with all the necessary elements:
Several of our tags have IDs so that we can reference them later. Also note the 'galleryimg="no"' tags on two of our images. This is to prevent IE from adding its image menu to the large color picker image and its background. Also note that this should be created with JavaScript like our horizontal color picker.
Pulling it all Together
We have our horizontal color picker and we have the layout for our larger one. All that's left is to attach functions to our elements as follows:
- The color picker needs a mousemove function that changes the color of the "current color" div. This should only happen when the mouse button is down.
- The R, G and B input boxes should also change whenever the color is changed.
- The color slider needs to change the background color of the color picker. This should happen on both click and mouse move events when the mouse button is down.
- The same thing should happen with the arrows on the side of the color picker, and which need to be dragged..
- The R, G and B input boxes should change both the current color and the background color of the color picker.
- The "start color" div should reset our color picker.
- Clicking the "Web safe" image at the top right should select the closest Web safe color.
- The "Web safe" image at the top right should dissapear if a Web safe color is selected.
- The checkbox should make the color picker only select the nearest Web safe color.
- Clicking the icon at the top-right should revert to our horizontal color picker.
Before we start on this list, we're going to create a small object that will cache references to all of the HTML objects in our color picker. This will make our script much faster as we won't have to call document.getElementById thousands of times in our script.
Pretty simple, right? We simply list out all of our element's ids and cache references to each one. We also created 4 variables for use later. These simply store the mouse state (up or down) and the position on screen of the color picker or color slider.
These will be used extensively throughout the rest of our script.Looking through our list of requirements, there are two helper functions we need to write. One function needs to get a "Web safe" color; the other needs to parse a hex color into its elements so that we can use it. First, the function for Web safe colors:
As you may have guessed, a WebSafe color is simply defined as having the RGB values all divisible by 51. Why 51? Well, 33 in hex converts to 51. So hex codes like #003366 and #99CCFF are both valid Websafe colors because 00, 33, 66, 99, CC and FF are all the valid hex values divisible by 51.
So what our function does is round each of the RGB values to the nearest multiple of 51 and then returns an object with these values.
Next, a function to parse RGB values out of a hex color string. How do we convert the value 'FF' to the number 255? Well, fortunately for us, this is a lot easier than it may seem at first. JavaScript has a built in feature where if a value starts with 0x, it's automatically assumed to be a hex value. So 0xFF = 255. We can therefore split a hex string like #FFCC66 into 3 part, "FF", "CC" and "66", prepend '0x' to each and eval() them:
Next we are going to make functions for each of our events: MouseDown functions, MouseUp functions, etc. It's generally a good practice to start by creating all the functions you think you'll need and then filling in the workings of each one as you go. If you happen to need another function later, go ahead and create another!
As you can see, the two mouseDown functions simply flag the mouse as being down and store the position of their respective objects. The mouseUp functions unflag the mouse as being down and that's it. So what do we do with this information? Well, you might have noticed that the cpMouseMove function is attached to document.onmousemove, meaning it will be fired whenever the mouse is moved anywhere on the page. This function will check our two flags, cpMouseDown and SliderMouseDown and fire additional code if necessary.
Another thing to note is that none of our functions have any arguments passed to them. The only argument we really need for this script, in adition to the mouse button state, is the mouse position. We will be getting this from the event object and the mouseCoordinates function we wrote earlier.
You might be wondering why this check is in document.onmousemove and not attached to the mousemove functions of the elements themselves. If we attached the mousemove functions to the specific elements, they would only fire when the mouse was exactly over the items. I'm sure you can imagine how annoying this might be for the arrows in particular. If your mouse strayed off the small 9px high image, you'd lose functionality until you moved the mouse back to exactly the right spot. By attaching all functionality to document.onmousemove instead, we avoid this problem completely.
The foundation for our color picker is now set. We just have to make these few functions work. First, we'll write the two functions that actually set the color and set the slider position. These are the foundation for changing any colors on our color picker:
We then get the Websafe equivalent of our current color. We're going to be using this no matter what, either to verify that the current color is Websafe or to set the background color of our little Websafe color icon.
If our Websafe checkbox isn't checked, we show and set the background color of the "make Websafe" image. If not, we set our color variable to our Websafe color and hide the "make Websafe" image.
Finally, we change the values of our RGB input boxes and change the current color. There's a lot to this function, so read through it to make sure you understand it all.
Moving on to the function for the slider:
We then save the current color for later, and finally swap out the background color for our color picker, which changes the look of the entire thing!
From here, we're almost home free. We have all our our functionality taken care of, we just need to activate it:
The cpMouseClick function simply calls the setCPColor function we just wrote, using the mouse position and the getGradientColor function we created earlier in this tutorial.
The cpSliderClick function does exactly the same thing, but with the vertical color slider.
As mentioned earlier, the cpMouseMove function is going to tie it all together. If the mouse is down on the color picker, we fire the cpMouseClick function. If the mouse is down on the slider, we fire the cpSliderClick function.
Voila! Everything now works! But we're still missing two little pieces of functionality:
The selectWebSafeColor function fires when the user clicks the "make Websafe" image near the top right of our color picker. It sets the current color by figuring out the closest Web safe color to the current one.
The resetColor function does exactly what it sounds like - it resets the color picker to whatever color it was when it was opened. The cp.origColor variable must be stored when the color picker is first opened.
Demo
Using this code as well as the previous functions we created, we're able to make our color picker fully functional. The final thing that needs to be done is to make the "toggle" icon at the bottom right of our horizontal color picker open the larger color picker, and vice-versa. This is already done in the examples above and it's left to the reader to figure out how to do this.
Conclusion
The end! We now have our fully functional dual-mode color picker. Clicking any of the above three input boxes should show you this. If you would like to use this on your own site I've provided a zip file that contains all of the necessary files, including the completed colorpicker.js file.
There is always room to improve, however. The version included in the
.zip file, for instance, includes an object used to translate color
names (such as "red,""teal," etc.) into their approprite hex color
codes. One of the simplest improvements would be to make an
image to surround our color picker, or to make two different sizes of
the large color picker as opposed to using the horizontal one we
created. Have fun!



Created: March 27, 2003
Revised: Sept 1, 2006
URL: http://webreference.com/programming/javascript/mk/column3/1
Information Technology Manager (MN)
Next Step Systems
US-MN-Minneapolis
SR UI DEVELOPER - JSF - Ajax - ICE Faces - Rich Faces
Next Step Systems
US-IL-Chicago
Technical Specialist – Pre-sales (MA)
Next Step Systems
US-MA-Littleton


