Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

A Color Picker Control

3.14/5 (4 votes)
14 Sep 2007CPOL 1   194  
An client-side color picker control using JavaScript.

Screenshot - ColorPiker1.jpg

Introduction

I was working on an ASP.NET project and came across the requirement for a color picker. I searched on the net for one and I came across a dropdwonlist selector and popup control. But it was not what I was looking for, so I created one which suited my requirements. Well, it's a simple one, and does solve my problems to an extent.

Using the code

We are using an HTML table where each cell has a different color. On clicking a link, this table will hide/show. When the user click on a cell, a JavaScript function is called, which assigns the color code to the textbox. Each table cell has its background color attribute set. On clicking a cell, we calling the JavaScript function onclick="javascript:toggleLayer( 'color1' , this,'TextBox1');", which will set the selected cell's background color to that of the textbox.

Here is the JavaScript:

JavaScript
//
function toggleLayer( whichLayer, Colorcntrl ,txtboxcntrl)
{
  var elem, vis;
      if( document.getElementById ) 
        elem = document.getElementById( whichLayer );
            else if( document.all )
                    elem = document.all[whichLayer];
                        else if( document.layers )
                            elem = document.layers[whichLayer];
  vis = elem.style;
  
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
      vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
  
  //Set Textbox value and background
  if(Colorcntrl != null && txtboxcntrl != null)
  {
    document.getElementById(txtboxcntrl).value = Colorcntrl.style.backgroundColor;
    document.getElementById(txtboxcntrl).style.backgroundColor = 
                                         Colorcntrl.style.backgroundColor;
  }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)