Random RGB / Hex Generator
HTML
<table>
<thead>
<tr>
<th></th>
<th>R</th>
<th>G</th>
<th>B</th>
</tr>
</thead>
<tr class="box">
<td><b>Text</b></td>
<td><input class="slider red" type="text" value="0" maxlength="3"/></td>
<td><input class="slider green" type="text" value="0" maxlength="3"/></td>
<td><input class="slider blue" type="text" value="0" maxlength="3"/></td>
<td><button class="rand">RANDOM</button></td>
</tr>
<tr class="bg">
<td><b>Back</b></td>
<td><input class="slider red" type="text" value="0" maxlength="3"/></td>
<td><input class="slider green" type="text" value="0" maxlength="3"/></td>
<td><input class="slider blue" type="text" value="0" maxlength="3"/></td>
<td><button class="rand">RANDOM</button></td>
</tr>
</table>
<div id="colorBox"></div>
CSS
body {
font-family: arial;
}
table {
border-collapse: collapse;
text-align: center;
margin: 0 auto 20px;
}
table td:first-child {
text-align: right;
padding-right: 10px;
}
label {
font-weight: bold;
}
input {
width: 60px;
text-align: center;
}
#colorBg {
padding: 40px;
border-radius: 5px;
text-align: center;
transition: all .5s;
}
#colorBox {
float: left;
height: 100px; width: 100px;
margin-right: 20px;
border-radius: 5px;
transition: all .5s;
}
#colorText {
float: right;
transition: all .5s;
font-weight: bold;
font-size: 60px;
line-height: 100px;
}
#colorBg .wrapper {
display: inline-block;
}
JavaScript
function toHex(i) {
if(!isNaN(i)) {
var hex = i.toString(16);
if(hex.length==1) hex = '0'+hex;
return hex;
}
else return '0';
}
function randomRGB() {
var c = {};
c.r = Math.floor((Math.random() * 255));
c.g = Math.floor((Math.random() * 255));
c.b = Math.floor((Math.random() * 255));
return c;
}
function updateBox(c) {
var rgb = 'rgb('+c.r+','+c.g+','+c.b+')';
$('#colorBox').css('background-color', rgb);
$('#colorText')
.html('#'+toHex(c.r)+toHex(c.g)+toHex(c.b))
.css('color', rgb);
}
function updateBg(c) {
var rgb = 'rgb('+c.r+','+c.g+','+c.b+')';
$('#colorBg').css('background-color', rgb);
}
function initBox() {
var c = randomRGB();
$('.box .slider.red').val(c.r);
$('.box .slider.green').val(c.g);
$('.box .slider.blue').val(c.b);
updateBox(c);
}
function initBg() {
var c = randomRGB();
$('.bg .slider.red').val(c.r);
$('.bg .slider.green').val(c.g);
$('.bg .slider.blue').val(c.b);
updateBg(c);
}
$('.slider').on('keyup', function () {
var tr = $(this).closest('tr');
var c = {};
c.r = parseInt(tr.find('.slider.red').val());
c.g = parseInt(tr.find('.slider.green').first().val());
c.b = parseInt(tr.find('.slider.blue').first().val());
if(tr.hasClass('box')) updateBox(c);
else if(tr.hasClass('bg')) updateBg(c);
});
$('.box .rand').on('click', function () {
initBox();
});
$('.bg .rand').on('click', function () {
initBg();
});
initBox();
initBg();