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).
Defaults:
- 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.
Extras:
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:
CODE
function createcp(OBJ,CELLWIDTH,CELLHEIGHT,CELLSPACING,CELLPERROW,COLORARR)
{
// 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
CODE
// create <div> element then assign it to DIV variable.
DIV=document.createElement("div")
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).
CODE
// Set OBJ argument as: an ID to DIV element.
DIV.id=OBJ
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)
CODE
// Set default style properties to DIV.
DIV.style.background="#ECE9D8"
DIV.style.borderWidth=1
DIV.style.borderColor="black"
DIV.style.borderStyle="solid"
DIV.style.visibility="hidden"// Hide DIV.
DIV.style.position="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)
CODE
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.
CODE
// 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)
COLORARR=Array(
"black","brown","#005110","darkgreen","#003366","darkblue","indigo","#333333",
"darkred","#FF6600","olive","green","teal","blue","#666699","gray",
"red","#FF9900","#99CC00","seagreen","#33CCCC","#3366FF","purple","#999999",
"fuchsia","gold","yellow","lime","cyan","skyblue","#993366","#C0C0C0",
"#ff99cc","#ffcc99","#ffff99","#ccffcc","#ccffff","#99ccff","#cc99ff","white"
)
We will continue validating all arguments if passed; or assigning it (to default values we need) if not
CODE
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.
CODE
TBL=document.createElement("table")// creating the table
Then let's adjust the table cells spacing to (CELLSPACING) argument value.
CODE
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)
CODE
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.
But….
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.
CODE
// creating a new <tr> element each time TR filled up with an amount of TD equals to CELLPERROW then assign it to TR variable.
if(i%CELLPERROW==0){
TR=document.createElement("tr")
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.
CODE
// Creating a new <td> element then assign it to TD variable.
TD=document.createElement("td")
// 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.
TD.unselectable="on"
// Changing the cursor to a hand style.
TD.style.cursor="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.
TD.style.fontSize=0
// Show color’s value as a tip when the mouse moves over a cell.
TD.title=COLORARR[i]
// Set default cells border color.
TD.style.borderColor="#ffffff"
// Set default cells border style.
TD.style.borderStyle="solid"
//Set default border cells width.
TD.style.borderWidth=1
// Change the cells width to CELLWIDTH we passed to the function.
TD.style.width=CELLWIDTH
// Change the cells height to CELLHEIGHT we passed to the function.
TD.style.height=CELLHEIGHT
// Read a colors value then assign it to TD's background color depending on the loop’s counter.
TD.bgColor=COLORARR[i]
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.
CODE
// at run time OBJ represents the whole Div
TD.onclick=OBJ+".CurrentColor=this.bgColor;"+OBJ+".Hide()"
// Change cell border color when the mouse moves over a cell.
TD.onmouseover="this.style.borderColor='#000000'"
// Change cell border color when the mouse moves out of a cell.
TD.onmouseout="this.style.borderColor='#ffffff'"
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.
CODE
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
CODE
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).
CODE
// Adding Left Method to the DIV element, if x not passed the Method returns DIV's left.
DIV.Left=function(x){if(x==undefined)return this.style.left;else this.style.left=x;}
The same thing with (Top) Method.
CODE
// Adding Top Method to the DIV element, if y not passed the Method returns DIV's top.
DIV.Top=function(y){if(y==undefined)return this.style.top;else this.style.top=y;}
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.
CODE
// Hide color picker.
DIV.Show=function(){this.style.visibility="visible"}
// Show color picker.
DIV.Hide=function(){this.style.visibility="hidden";}
//Return color picker visibility status.
DIV.Visibility=function(){return this.style.visibility}
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.
CODE
// 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 this.style.borderWidth; else this.style.borderWidth=d;}
// 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 this.style.borderStyle; else this.style.borderStyle=s;}
// 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 this.style.borderColor; else this.style.borderColor=c;}
// 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 this.style.background; else this.style.background=c;}
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.
CODE
document.body.appendChild(DIV)
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
CODE
<head>
<script language=”javascrip”>
// Add the code here
</script>
</head>
- write the function on any plain text editor like note pad, then save it as .js file.
CODE
<html>
<head>
<script language=javascrip src="the url to your .js file"></script>
1- Create a color picker with all defaults
CODE
createcp("cp1")
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).
CODE
createcp("cp2",10,10,6,8)
3- Create the a color picker with specific color list
CODE
colors=Array("red","green","blue","yellow","navy","#ff3300","rgb(120,10,200)","orange")
createcp("cp3",10,10,2,4)
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
CODE
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
CODE
alert(cp5.Visibility())
V=cp5.Visibility()
6- Changing color picker positions
CODE
cp6.Left(100)// Changing color picker’s left position
cp6.Top(50)// Changing color picker’s top position
7- Getting color picker positions
CODE
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)
CODE
cp8.BorderStyle("dotted")
9- Getting color picker’s border style
CODE
alert(cp9.BorderStyle())
10- Changing color picker’s border color
CODE
Cp10.BorderColor("red")
11- Getting color picker’s border color
CODE
alert(cp11.BorderColor())
12- Changing color picker’s border width
CODE
cp12.BorderWidth(4)
13- Getting color picker’s border width
CODE
alert(cp13.BorderWidth())
14- Changing color picker’s background color
CODE
Cp14.BgColor("yellow")
15- Getting color picker’s background color
CODE
alert(cp15.BgColor())
16- Getting the selected color
CODE
alert(cp16.CurrentColor)
And that’s all
For testing issues I attached an HTML file includes all properties we can control.
Click to view attachment
I hope you can find something helpful in this tutorial.
Any suggestions or comments are welcome.
Best regards