Color dice

A dice for a random color.

by Erik Wegner

HTML

<div id="dice">
</div>
<div id="timer">
</div>

CSS

#dice {
  width: 100%;
  background-color: #ffa;
}
#timer {
  height: 10px;
  background-color: #faf;
}
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden !important;
}

JavaScript

// public
var colors = ['#f99', '#9f9', '#99f', '#ff9', '#f9f', '#9ff', '#999']

// private
var colorcount = colors.length;
var colorindex = 0;
var intervalHandle = 0;
var time = 100;
var dice$ = jQuery('#dice')
var timer$ = jQuery('#timer')

function rollingDice() {
  time--;
  if (time < 0) {
    // final color reached
    clearInterval(intervalHandle);
    intervalHandle = 0;
    time = 100;
    return;
  }

  // update timer bar
  timer$.css('width', time + '%');
  // select a new color
  colorindex = (colorindex + parseInt(Math.random() * colorcount)) % colorcount
  // update dice
  dice$.css('background-color', colors[colorindex]);
}

dice$.on('click', function() {
  // if dice is rolling, do nothing
  if (intervalHandle > 0) {
    return;
  }

  // start rolling the dice
  intervalHandle = setInterval(rollingDice, 15);
})

dice$.css('height', (window.innerHeight - 10) + "px")