JavaScript Web-Safe Colour Palette Generator
7
A websafe colour palette generator in JavaScript. Coded this after looking at http://www.bytemycode.com/snippets/snippet/585/ and wanting to do it differently.
It's been refactored so that:
* can pass generateColourPalette an arbitrary array of colour codes and it'll generate a palette.
* it hooks into the page through the external file
* uses an internal stylesheet instead of inline styles
It's been refactored so that:
* can pass generateColourPalette an arbitrary array of colour codes and it'll generate a palette.
* it hooks into the page through the external file
* uses an internal stylesheet instead of inline styles
// Generates and array of strings containing all 216 web-safe colour codes
function getWebsafeColours() {
var colours = [];
var hex;
var parts = ["00", "33", "66", "99", "cc", "ff"];
for (var i=0; i < 216; i++) {
colours.push("#" +
parts[Math.floor(i/36)] +
parts[Math.floor((i/6)%6)] +
parts[i % 6]);
}
return colours;
}
// Populates the div called "palettes" in the webpage using the colours passed in
function generatePalettes(colours) {
var palettes = document.getElementById("palettes");
for (var i=0;i<colours.length; i++) {
var palette = document.createElement("div");
palette.className="palette";
palette.style.backgroundColor = colours[i];
palette.innerHTML = "<a href='#' onmouseover=\"document.getElementById('colour').innerHTML = '" + colours[i] + "'\"> </a>";
palettes.appendChild(palette);
}
}
// Populate the palette once the page is done loading
window.onload= function() {
generatePalettes(getWebsafeColours());
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
#palettes {
width: 430px;
}
.palette {
width: 30px;
float: left;
text-align: center;
padding: 2px;
}
.palette a {
display: block;
text-decoration: none;
}
#colour {
font-weight: bold;
}
</style>
<script type="text/javascript" src="websafe.js"></script>
</head>
<body>
<h1>Web-Safe Colour Palette</h1>
<h2>All 216 colours</h2>
<p>Colour Code: <span id="colour"></span></p>
<div id="palettes"></div>
</body>
</html>






I've change the code and it works properly.
Regards,
Kumar S
GuyFromChennai.com
function generatePalettes(colours) {
var palettes = document.getElementById("palettes");
for (var i=0;i<colours.length; i++) {
var palette = document.createElement("div");
palette.className="palette";
palette.style.backgroundColor = colours[i];
palette.setAttribute("title", colours[i]);
palette.style.height ='10px';
palette.style.width = '10px';
palette.setAttribute("onmouseover", "document.getElementById('colour').innerHTML=\'" + colours[i]+"\'");
palettes.appendChild(palette);
}
}