CSS Generator
by Ryan Perez
HTML
<form>
<table>
<tbody>
<tr>
<td>
<input type="text" name="primary" value=""> </td>
</tr>
<tr>
<td>
<input type="text" name="secondary" value=""> </td>
</tr>
<tr>
<td>
<input type="text" name="primary-comp" value=""> </td>
</tr>
<tr>
<td>
<input type="text" name="secondary-comp" value=""> </td>
</tr>
<tr>
<td>
<input type="text" name="add-comp" value=""> </td>
</tr>
<tr>
<td>
<input type="text" name="shade" value=""> </td>
</tr>
<tr>
<td>
<input type="text" name="highlight" value=""> </td>
</tr>
</tbody>
</table>
</form>
<div id="cssValues">
</div>
JavaScript
// Define global object
var colorList = {}, counter = 0;
// Get the inputs
$('input').each(function() {
var nameOfInput = $(this).attr('name');
$(this).attr('placeholder', nameOfInput);
$(this).attr('data-counter', counter);
counter++;
// Add event listener for input change
$('input').on('change',function(){
if ($(this).val().length < 1) {
delete colorList[$(this).attr('data-counter')];
} else {
// Check for proper color format
var colorVal = '';
if ($(this).val().charAt(0) != '#') {
colorVal = '#'+$(this).val();
} else {
colorVal = $(this).val();
}
colorList[$(this).attr('data-counter')] = {
name: $(this).attr('name'),
value: colorVal
};
// If you want, you can put code here to apply the color to a preview element next to the box
}
updateCSS();
});
});
function updateCSS() {
var returnCSS = '';
var colorsLength = Object.keys(colorList).length;
for (var i=0;i<colorsLength;i++) {
returnCSS += generateRule(colorList[i].name,colorList[i].value);
}
$('#cssValues').html(returnCSS);
}
function generateRule(color, colorCode) {
var response = '.brand-color-'+color+'-background {<br> background-color: '+colorCode+' !important;<br>}';
response += '<br>.brand-color-'+color+'-text {<br> color: '+colorCode+' !important;<br>}<br>';
return response;
}