Creating a count down meter with CSS3 and JQuery

Whilst work­ing on the Math­DO­JO mini game one of the neat lit­tle things I tried to do was imple­ment a time meter which steadi­ly counts down and changes colour (from green to yel­low to glow­ing red) as it approach­es 0:

image

image

image

First, you need some­thing to rep­re­sent the meter, a sim­ple <span> ele­ment 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 ani­ma­tion which for now, is only sup­port­ed by webkit brows­er unfor­tu­nate­ly) at dif­fer­ent 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 ani­ma­tion itself is han­dled by Javascript, using JQuery’s ani­mate 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 after­wards, it’s eas­i­est to remove the “style” attribute as JQuery applies the changes through the “style” attribute, which can be a prob­lem if you had man­u­al­ly insert­ed 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.