I have a unique idea for creating a dynamic four-square box that changes colors at random every time a button is clicked. The twist is, I want the colors to cycle randomly for up to 5 seconds before 3 out of 4 squares turn black and one square stops on a random color.
While browsing online, I came across this interesting jsfiddle snippet http://jsfiddle.net/cQB38/1/, which is almost what I'm looking for but lacks the timed element. I tried incorporating setInterval into the code but couldn't quite get it working. Here's the script from the jsfiddle:
HTML
<div onclick="change_color(2)" id="div_color_2" class="ne change_color" style="background-color: rgb(94, 198, 49);">
</div>
...
<!-- Random me button that selects a random color for each square -->
<input id="question" type="button" onclick="colorfy_me()" value="Random me">
<!-- the squares -->
<p id="square1">Square 1</p>
...
JAVASCRIPT
var myColors = [
'#7F8C8D', '#95A5A6', '#BDC3C7', '#003946', '#BDC3C7',
...
// Function to apply random colors to the squares
colorfy_me = function() {
var colors = myColors.slice(0)
$('div.change_color').each(function() {
// Pick a random color not in use.
var color = Math.floor(Math.random() * colors.length);
$(this).css('background-color', colors[color]);
$(this).html( colors[color] )
colors = colors.slice(0,color-1).concat( colors.slice(color+1,colors.length-1) )
});
$.each(colors, function(i, v){
$('#div_color_' + (+i + 1)).html(colors[i])
});
}
...
CSS
[CSS styles here]
If anyone has a solution or any ideas on how to add timing functionality to this project, I would appreciate your input. Thank you!