Previous Page
Next Page

Web-safe Colors

Have you ever wished for a handy online table of Web-safe colors, complete with hex codes? The ones printed in books (and magazines, and even mousepads) never quite match the colors of your monitor. Script 17.4 shows how you can use a bookmarklet to display a Web-safe color table at any time.

Script 17.4. This script creates a table of Web-safe colors.

javascript:var i,j,k,l,t='<table width=100%>', c=new Array('00','33','66','99','CC','FF');
 for(i=0;i<6;i++){for(j=0;j<6;j++){t+= '<tr>';for(k=0;k<6;k++){l=c[i]+c[j]+c[k];t+= '<td 
bgcolor=#'+l+'>'+l+'</td>'}t+= '</tr>'}}void(document.body.innerHTML= t+'</table>');

To show a Web-safe color chart:

javascript:var i,j,k,l,t='<table width=100%>',

The bookmarklet, as always, starts with javascript:. This line also declares the variables i, j, k, l, and t. That last variable starts to create the table that's later going to be written out.

c=new Array('00','33','66','99', 'CC','FF');

Here we create a new array, c, which contains all the valid Web-safe color values for red, green, and blue.


The i loop follows the red values. Note that when it is appropriate to use a {, it also serves as a separator.


The j loop follows the green values.


Each row will contain the six color values where the red and green values stay constant, but the blue values vary.


The k loop follows the blue values.


The variable l will contain each of the 216 values, from "000000" to "FFFFFF", as the three loops vary.

t+='<td bgcolor=#'+l+'>'+l+'</td>'}

Each cell in the table is assigned a background color and contains the hex value of that color. This step also ends the k loop.


The table row ends here, as do the j and i loops.

void(document.body.innerHTML= t+'</table>'

When all the loops are complete, reset document.body.innerHTML with the contents of our color chart plus a closing table tag. This displays the entire page, as shown in Figure 17.12.

Figure 17.12. The result of this script is a nicely laid out table of Web-safe colors.


  • As mentioned in this chapter's introduction, a bookmarklet must be a single line of code. Putting the semicolons between statements allows you to put all the commands on a single line.

Previous Page
Next Page