Autogenerate Colours
by Anton
HTML
<div>
<label>Qty: </label><input id="gen-qty" type="text" name="qty" value="16"><button id="gen-btn">Generate</button>
</div>
<ul id="colour-show-1"></ul>
<ul id="colour-show-2"></ul>
CSS
ul {
float: left;
list-style: none;
padding-left: 10px;
margin-right: 10px;
}
li {
width: 200px;
line-height: 25px;
}
JavaScript
$('#gen-btn').click(generate);
function generate() {
var genQty = $('#gen-qty').val();
populateList('#colour-show-1', genQty, 0);
populateList('#colour-show-2', genQty, 1);
}
// variant is the choice of which method to apply
// 0 - basic; 1 - with the odd/even saturation/lightness trick
function populateList(selector, qty, variant) {
var html = "", colour;
var step = Math.floor(360 / qty);
for(var i = 0; i < qty; i++) {
colour = getColour(i, step, variant);
html += '<li style="background-color: ' + colour + ';"> </li>';
}
$(selector).html(html);
return;
}
function getColour(num, step, variant) {
var col;
switch (variant) {
case 1:
col = 'hsl(' + (num * step).toString() + ', ' // Hue
+ ((num % 2 == 0) ? 80 : 75) + '%, ' // Saturation, even/ odd
+ ((num % 2 == 0) ? 70 : 80) + '%)'; // Lightness, even/odd
break;
default: col = 'hsl(' + (num * step).toString() + ', 80%, 70%)';
}
return col;
}