Creating a count down meter with CSS3 and JQuery

Whilst working on the MathDOJO mini game one of the neat little things I tried to do was implement a time meter which steadily counts down and changes colour (from green to yellow to glowing red) as it approaches 0:

image

image

image

First, you need something to represent the meter, a simple <span> element will do:

   1: <body>

   2:     <span id="count-down-meter"></span>

   3: </body>

Then you need CSS to define its colour (and glow effect using CSS3 animation which for now, is only supported by webkit browser unfortunately) at different stages

   1: /* define the animation (webkit-only) */

   2: @-webkit-keyframes redPulse

   3: {

   4:     from { -webkit-box-shadow: 0 0 9px #f00; }

   5:     50% { -webkit-box-shadow: 0 0 18px #f00; }

   6:     to { -webkit-box-shadow: 0 0 9px #f00; }

   7: }

   8:

   9: /* initial state of the meter */

  10: #count-down-meter

  11: {

  12:     display: block;

  13:     width: 100%;

  14:     height: 15px;

  15:     margin-top: 10px;

  16:     background-color: #0f0;

  17: }

  18:

  19: /* change color at midway */

  20: #count-down-meter.middle

  21: {

  22:     background-color: #ff0;

  23: }

  24:

  25: /* change colour and play animation when it's on its last leg */

  26: #count-down-meter.lastleg

  27: {

  28:     background-color: #f00;

  29:     -webkit-animation-name: redPulse;

  30:     -webkit-animation-duration: 2s;

  31:     -webkit-animation-iteration-count: infinite;

  32: }

The animation itself is handled by Javascript, using JQuery’s animate method:

   1: function start() {

   2:         // change to yellow when 40% way through

   3:     var midWidth = meter.width() * 0.6,

   4:         // change to glowing red when 70% way through

   5:         lastlegWidth = meter.width() * 0.3;

   6:

   7:     meter.animate({

   8:         width: 0 + "px",

   9:     }, {

  10:         duration: 5000,

  11:         easing: "linear",

  12:         step: function(now, fx) {

  13:             if (now <= midWidth) {

  14:                 meter.addClass("middle");

  15:

  16:                 if (now <= lastlegWidth) {

  17:                     meter.addClass("lastleg");

  18:                 }

  19:             }

  20:         }

  21:     });

  22: };

To reset the state changes to the meter afterwards, it’s easiest to remove the “style” attribute as JQuery applies the changes through the “style” attribute, which can be a problem if you had manually inserted style in your HTML:

   1: function reset() {

   2:     meter.stop()

   3:          .removeAttr("style")

   4:          .removeClass("middle")

   5:          .removeClass("lastleg");

   6: };

Here’s a live demo:

So that’s it, nice and easy! Enjoy! Hope you find some good use for it.