I have a function that can generate random colors. I would like to utilize this function along with jQuery's toggleClass feature to change the color of a table cell when clicked, and revert it back to its original color if clicked again.
Here is the HTML structure of the table:
<div id="container">
<table id="table">
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</div>
This is the color generation function in JavaScript:
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
Here is how the color assignment to the table cell can be done using jQuery:
$(function(){
$('td').click(function(){
$(this).css('background-color', getRandomColor());
});
});