. How to Create a Color Picker in JavaScript - WebReference.com-

spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / mk / column3 / 1 To page 1To page 2To page 3current page
[previous]

KRONOS Technical Analyst
Professional Technical Resources
US-OR-Portland

Justtechjobs.com Post A Job | Post A Resume
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

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:

  1. 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.
  2. The R, G and B input boxes should also change whenever the color is changed.
  3. 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.
  4. The same thing should happen with the arrows on the side of the color picker, and which need to be dragged..
  5. The R, G and B input boxes should change both the current color and the background color of the color picker.
  6. The "start color" div should reset our color picker.
  7. Clicking the "Web safe" image at the top right should select the closest Web safe color.
  8. The "Web safe" image at the top right should dissapear if a Web safe color is selected.
  9. The checkbox should make the color picker only select the nearest Web safe color.
  10. 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:

For "CC", for example, you get CC --> 0xCC --> 204. This is much simplier than writing a parsing script ourselves from scratch!

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:

The setCPColor function will attempt to get a color in 3 steps: if a color object is passed into it, i.e. {r:255, g:255, b:255}, it will accept this. Next, we attempt to parse any hex string passed into the function, and to do this we use the parseColor function we just wrote. Finally, if we still don't have a color, we grab information from our RGB input boxes and create a color from that.

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:

This short little function does quite a bit. First, we make sure y is between 0 and 255. If it's not, we make it so. We then move the arrows to their appropriate position, which happens to be 18px from the top of our color picker. Why 18px? This is the distance from the top of the vertical color picker to the top of the entire color picker - half the distance of the arrow image so that the arrow appears to be pointing at the appropriate color.

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!

Select Color:
Click to Select Web Safe Color
R:
G:
B:
Only Web Colors

home / programming / javascript / mk / column3 / 1 To page 1To page 2To page 3current page
[previous]

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
  PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
HP eBook: Guide to Storage Networking
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Crucial Triples Up With New Three-Channel DDR3 Kits · Meet the Finalists: Excellence in Technology Awards · Tealeaf Offers Insight to Mobile Customer Behavior

Created: March 27, 2003
Revised: Sept 1, 2006

URL: http://webreference.com/programming/javascript/mk/column3/1