Page 1 of 1

How To Create Color Picker Rate Topic: -----

#1 ahmad_511   User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Post icon  Posted 19 October 2007 - 03:55 PM

How to create color picker object?
1- The point.
2- Defaults
4- What to pass?
5- What to get?
6- Extras.
6- How to do it?
7- Using color picker

The point:
The point of this tutorial is to let us know how to create a color picker that we can use several times at the same document and each one still has its own properties, so we can control each one separately.
We will let Javascript creates all elements we need. So we donít need to spend time creating color table, formatting and assigning properties for each one.
And thatís will decreases the page loading time. There is a fact says (less bytes you write, less time you need to load).


- Cell height = 8
- Cell width = 8
- Cells spacing = 1
- Cells per row = 8
- Colors list = MS Word default font colors
- Current selected color = ďblackĒ.
- Color picker's visibility = ďhiddenĒ
- Color picker's left = 0
- Color picker's top = 0
- Color picker's border style = ďsolidĒ
- Color picker's border color = ďblackĒ
- Color picker's border width = 1
- Color picker's background color = ď #ECE9D8Ē

What to pass:
- We need to pass 3 required arguments to the color picker creator function.

OBJ: An ID handles the color picker after creating it. (String).
CELLWIDTH: Width of color-cell in pixels. (Integer).
CELLHEIGHT: Height of color-cell in pixels. (Integer).

- And 3 optional arguments:

CELLSPACING: The space between cells. (Integer).
CELLPERROW: How many cells we want to show in each row of the color picker's grid. (Integer).
COLORARR: Colors we want to use in color picker. (Array).

What to get:
- Color picker with specifics we pass.
- Show / hide the color picker on demand.
- Returning Show / hide status.
- Set / Return the color-pickerís left position.
- Set / Return the color-pickerís top position.
- Set / Return the color-pickerís border style.
- Set / Return the color-pickerís border color.
- Set / Return the color-pickerís border width.
- Set / Return the color pickerís background color.
- Return the current selected color.

We want to:
- Change the cursor style to a hand when it moves over the cells
- Change the cells border color to Black when the mouse moves over the cells and return it to White when it moves out.
- Show the color's name or value as a tip when the mouse moves over a cell.
- Hide the color picker after selecting a color

How to do it:
First, we need to create a function to do the entire job for us, so let's call it "createcp" and pass it some necessary arguments to complete the tasks:

The function:
// The next codes will be placed here.

Creating a box to contain our color picker then setting up some defaults.
To do that first thing we need is to create a (Div) element using createElement Method
// create <div> element then assign it to DIV variable.

Now let's add the (ID) we passed to our function which is (OBJ) argument, so that way we can control the whole color picker we creating right now by calling its (ID).
// Set OBJ argument as: an ID to DIV element.

To setup the first look of (Div) style we need to add some style properties
The default style we need to adjust are (back ground color, border width, border color, border style)
// Set default style properties to DIV."#ECE9D8""black""solid""hidden"// Hide DIV."absolute"// make DIV able to move freely anywhere on the document.

A few things to know when it comes to objects:
1-The id always identifies the object, so we can handle the object using its unique id.
2-we can add as many as we want of our own attributes to that object using its id or any referrer to it considering over writing the existing attributes, and later we can use it as variables relative to that object

According on that we will add now (CurrentColor) property to the (Div) elements, later we will refer to it using its id (OBJ)
DIV.CurrentColor="black"// Add CurrentColor property to DIV then assign it to balck.

We will check now if the color-array argument (COLORARR) is passed to the function or not, or it passed empty, and we will define our default colors which has the same colors and sequences of MS Word font color.
// If COLORARR not set and CELLPERROW not set,So set CELLPERROWS's value to 8
if((COLORARR==undefined || COLORARR.length==0) && (CELLPERROW==0 || CELLPERROW==undefined))CELLPERROW=8
// If we didn't pass COLORARR, set our default
if(COLORARR==undefined || COLORARR.length==0)

We will continue validating all arguments if passed; or assigning it (to default values we need) if not
if(CELLWIDTH==undefined)CELLWIDTH=8// CELLWIDTH  = 8 if we didn't pass it.
if(CELLHEIGHT==undefined)CELLHEIGHT=8// CELLHEIGHT  = 8 if we didn't pass it.
if(CELLSPACING==undefined)CELLSPACING=1// CELLSPACING  = 1 if we didn't pass it.
if(CELLPERROW==0 || CELLPERROW==undefined)CELLPERROW=COLORARR.length// CELLPERROW= COLOARR length If we didn't pass it or it's equals to 0

After validating done, we have to create a container for the colors, and usually it's a table, and we will create it the same way we created (Div) element before.
TBL=document.createElement("table")// creating the table

Then let's adjust the table cells spacing to (CELLSPACING) argument value.
TBL.cellSpacing=CELLSPACING// adjusting initial cells spacing

If you are boring right now, let's try having fun with looping.
First, let's make a loop starts at (0), increases by (1) till it arrives at colors count which is the color array's length (COLORARR)
for (i=0;i<COLORARR.length;i++)

Now let's work inside that pretty loop.
My plan is:
-create the first row, and then add it to the table.
-create cell by each loop
-add some styles, properties and methods
-add the cell to the row.
-when cells count reaches the total of cell-per-row value, we will create a new row and insert it into the table again.
After the loop is finished we will insert the table into the Div.

So creating elements is not matter after now, we will create it using the same way we created Div and table elements.
How to know when a row filled up with the required amount of cells?
Of course there is many ways to do that, but I preferred the shortest way in my view, which is getting the remainder of dividing loopís counter (i) on the cell-per-rowís variable (CELLPERROW). In other words we will use the Remainder operator ď%Ē to get the result.
Then if we got a result of (0) thatís means we reached our target and it's the time to create another row.
// creating a new <tr> element each time TR filled up with an amount of TD equals to CELLPERROW then assign it to TR variable.
TBL.appendChild(TR)// Append TR to TBL.

If you now have this question in your mind: We added an empty row! How can we append it cells after that?
Don't forget that we still have its referrer (TR), that's so we can control it whenever we want.
So adding or applying something to (TR) will affect the appended element directly.
(TR) now is ready to contain the colored cells, so letís start creating cells and add its style.
// Creating a new <td> element then assign it to TD variable.
// This following line will prevents users to select colored cells, which makes it have a good look if some one try to mess around with it.

// Changing the cursor to a hand style."hand"

// Adding space within TD (If we didn't add it we will have trouble changing cells border style, I don't know why but it happens on IE).
TD.innerText=" "

// Set the smallest font size for each <td> because of sizing issues.

// Show colorís value as a tip when the mouse moves over a cell.

// Set default cells border color."#ffffff"

// Set default cells border style."solid"

//Set default border cells width.

// Change the cells width to CELLWIDTH we passed to the function.

// Change the cells height to CELLHEIGHT we passed to the function.

// Read a colors value then assign it to TD's background color depending on the loopís counter.

Now things start getting serious.

Adding Events:
Before we start with events handling there is couple of things you need to know about events:
1- Events fires only at run time, and at run time we can handle any object by its own id or referrer.
2- (this) Keyword always refers to the element that received the event.

Weíre ready now to add some events:
The plan is:
-When somebody moves the mouse over a cell we need to change the cellís border color to black
-When somebody click on a cell we need to store the back ground color of that cell in the Divís CurrentColor property, so we can get back the selected color any time we want using Divís CurrentColor property.
-at last when somebody moves the mouse out of a cell we will return the cellís border color to white.

Letís go coding.
// at run time OBJ represents the whole Div
// Change cell border color when the mouse moves over a cell.
// Change cell border color when the mouse moves out of a cell.

You may ask: What (this) Keyword will do here?
At run time: (this) Keyword always refers to (TD) elements, but only at run time here.

Assuming that we pass OBJ=ĒMyColorPicker1Ē, thatís means our color picker now has an id=MyColorPicker.
After compiling the above code we will get (as result of applying "onclick" event) a string like this:
<TD onclick=ĒMyColorPicker1.CurrentColor=this.bgColor;MyColorPicker1.Hide()Ē>

Loop almost done, the last thing we have to do is putting TD element inside TR element which is already inside the table.
To do that, we will use (appendChild) Method.
TR.appendChild(TD)// Add TD element to TR element as the very last child in TR.

Now we completed working inside the loop. So letís put the colors table we created (using a loop) inside Div, then we will add some properties and defaults to that Div.
The table element (TBL) now contains all HTML code we need, so let's add this code (including tableís tag to the inner HTML code of Div element
DIV.innerHTML=TBL.outerHTML// insert TBL html into DIV html code.

Adding properties and methods

My plan here is to use the Method as an property if we didn't pass it arguments
For example:
Instead of declaring GetLeft to get back the left of the color picker, and declaring SetLeft to set the left property for the color picker, I think of it like the following:
What if we declared one Left Method, and then: if we passed the argument, that's means move the Div to the specified left position, if not return the Divís left position property.

How to create a Method?
Donít worry if you didnít familiar with Methods.
Itís just a function assigned to an object, in our case the object is (Div) element.

Letís start creating (Left) Method. (We capitalize the first letter L to separate it from the (left property) that is already exists into the most HTML elements).
// Adding Left Method to the DIV element, if x not passed the Method returns DIV's left.

The same thing with (Top) Method.
// Adding Top Method to the DIV element, if y not passed the Method returns DIV's top.

Thatís all what we need right now to control the position, but what if we want to control the visibility of color picker.
We will create two Methods to control color pickerís visibility (Hide/Show), and one Method to retrieve the visibility status.
We donít need to pass any variables here, so will create functions without arguments.
// Hide color picker.

// Show color picker.

//Return color picker visibility status.

The next Methods are just repeating for what we did with Left and Top Methods, so if you know how to do one of them you can do all others.
// Adding BorderWidth property then assign it to d, if d not passed the property returns DIV's borderWidth.
DIV.BorderWidth=function(d){if(d==undefined)return; else;}

// Adding BorderStyle property then assign it to s, if s not passed the property returns DIV's borderStyle.
DIV.BorderStyle=function(s){if(s==undefined)return; else;}
// Adding BorderColor property then assign it to c, if c not passed the property returns DIV's borderColor.
DIV.BorderColor=function(c){if(c==undefined)return; else;}

// Adding BgColor property then assign it to c, if c not passed the property returns DIV's backround color.
DIV.BgColor=function(c){if(c==undefined)return; else;}

Till now nothing appears on the document and every thing is stored in variables.
So letís bring it out to the document.
As you know when you are writing HTML, anything you want to come out on the screen must be in the body part of the document.
And for that reason we will append (DIV) with its all elements inside to the document's body element.

The end

Now and after we complete our function letís try it

Using color picker:

Before we can use it, we have to make sure that we put the function in the right place.
And there are two right places to write in
- within the documentís header by adding script tag like this
<script language=ĒjavascripĒ>
// Add the  code here

- write the function on any plain text editor like note pad, then save it as .js file.
<script language=javascrip src="the url to your .js file"></script>

1- Create a color picker with all defaults

2- Create a color picker with id="cp2",cell width=10,cell height=10,cell spacing=6, number of colors in each row=8.(we omitted the color list, so it will replaced with the default).

3- Create the a color picker with specific color list

As you can see above we can pass any color in any format.

Note: when you call (createcp) function you will not see anything on screen, thatís because we set the default visibility style of the DIV element to ďhiddenĒ

4- Show and Hide color picker
createcp("cp4") // we create default color picker
cp4.Show()// Show cp4color picker.
cp4.Hide()//Hide cp4 color picker.

5- Get color pickerís visibility status

6- Changing color picker positions
cp6.Left(100)// Changing color pickerís left position
cp6.Top(50)// Changing color pickerís top position

7- Getting color picker positions
alert(cp7.Left())// Getting color pickerís left position
alert(cp7.Top())// Getting color pickerís top position

8- Changing color pickerís border style.
Available style are (solid,dotted,dashed,double,groove,redge,inset,outset,none)

9- Getting color pickerís border style

10- Changing color pickerís border color

11- Getting color pickerís border color

12- Changing color pickerís border width

13- Getting color pickerís border width

14- Changing color pickerís background color

15- Getting color pickerís background color

16- Getting the selected color

And thatís all

For testing issues I attached an HTML file includes all properties we can control.
Attached File  colorpicker.htm (9.87K)
Number of downloads: 1723
I hope you can find something helpful in this tutorial.
Any suggestions or comments are welcome.

Best regards

Is This A Good Question/Topic? 0
  • +

Page 1 of 1