Skip to main content

Animated Charts with jQuery-Knob and jQuery.animate()

Front-end Development

Create a "Doughnut" Chart

jQuery-knob makes it easy to create dials that work well on desktop and mobile devices.  It can also be used to generate "doughnut" style charts.

Let's do that:

<input type="text" value="100" class="dial">
<script>
    $(".dial").knob();
</script>

Adding animation

Drawing a chart is great, but wouldn't it be nice if the chart animated from 0 to 100?  We can do this using jQuery's .animate() method.  In the following code, I use the example from Joss Crowcroft's blog post to animate the chart we created in the previous step.  

The .animate() method can be called on a hash object to animate all of the object’s properties, in our case the value of the input.  Here we are animating the value of the input from 0 to 100 over 2 seconds with swing easing.  On each step of the animation, the value of the input is updated, then the chart is updated using .trigger("change").

<input type="text" value="0" class="dial">

<script>
    $(".dial").knob();

    $({animatedVal: 0}).animate({animatedVal: 100}, {
       duration: 2000,
       easing: "swing", 
       step: function() { 
           $(".dial").val(Math.ceil(this.animatedVal)).trigger("change"); 
       }
    }); 
</script>

Animating at the right time

If the chart is in the viewport when the page loads, then our job is done!  If, however, the chart is further down the page, the animation probably won't be seen by the user.  To remedy this, you can combine the techniques above with jQuery-Waypoints to run the animation once the chart becomes visible.