DotNetCurry Logo

Create a jQuery Plugin to display a Running Counter

Posted by: Suprotim Agarwal , on 3/30/2015, in Category jQuery and ASP.NET
Views: 8860
Abstract: Use jQuery to create a Running Counter on your website to show a countdown to an event.

There are a number of ways to display a running counter in jQuery. For example, you can use the setInterval() function to run for a specific duration, increase the counter with every run and output it to a control. This gives you a running counter effect.

Alternatively we can also use the jQuery animate() function to create a running counter. We will use our newly acquired plugin knowledge and build a simple plugin which uses animate() to run a counter on a paragraph element between two numbers, for a specified duration. Something like this:

<p id="counter"></p>
$('#counter').runCounter({
    start: 0,
    end: 1000,
    duration: 10000
});

The above code runs a counter from 0 to 1000 in 10000ms or 10 seconds.

For this plugin, I won’t use our jQuery Boilerplate template. Infact not everybody uses the boilerplate template although they should, as it incorporates all best practices of plugin creation. Instead I will keep the plugin template very simple by stripping off some variables and objects we won’t require, and show you how to create a plugin using only the barebones.

Our plugin looks like the following. Put this Plugin in a separate .js file under the scripts folder and call it jquery.runCounter.js

;(function ($) {

    $.fn.runCounter = function (options) {
        var defaults = {
            start: 0,
            end: 0,
            duration: 1000
        };

        var opt = $.extend(defaults, options);

        return this.each(function () {
            var $para = $(this);
            $({ ctr: opt.start }).animate({ ctr: opt.end }, {
                duration: opt.duration,
                easing: 'linear',
                step: function () {
                    $para.text(Math.round(this.ctr));
                }
            });
        });
    }

})(jQuery);

Our plugin is defined as an IIFE function. Read more about IIFE function over here.

Although we have already learnt the basics of creating a plugin, I will explain most of the bits again just in case you need to revise some concepts.

We start by adding our function called runCounter to $.fn to make it available just like any other jQuery object method.

$.fn.runCounter = function () {}

The next step is to make our plugin customizable by accepting some options from the user. We use an object literal (comma separated list of name value pairs wrapped in curly braces) to specify the default options; in case the user doesn’t specify any.

var defaults = {
    start: 0,
    end: 0,
    duration: 1000
};

Using $.extend() we take the defaults and overwrite them with the options the user passed in.

var opt = $.extend(defaults, options);

The next piece of code is the each method

this.each(function () {}

Within the function, the value of this is the jQuery object on which your function was called. In our case, we used $('p').runCounter. So the value of this here refers to the jQuery object containing the result of $('p'), which refers to all the paragraphs on the page. This allows you to run your code on every paragraph element. This may or may not be what you want. You can give the paragraph an id and use the id selector if you want only one paragraph to run the counter.

Returning this by using return this.each makes your plugin chainable. So you can do something like:

$('p').runCounter().addClass('someClass');

Observe how we are using return this.each() instead of using return this at the end. The latter results in better readability, otherwise there is no difference between the two.

Once you are inside the loop, this refers to the DOM element which is not a jQuery object. So to make it a jQuery object and to run jQuery methods on it, we do

var $para = $(this);

Note: Don’t get confused with $para. You can call it anything you like. I usually refer to variables that contain jQuery objects as $variablename. At some places, I also use the same notation for a cached selector.

The next portion of the code is our jQuery animate() function

$({ ctr: opt.start }).animate({ ctr: opt.end }, {
    duration: opt.duration,
    easing: 'linear',
    step: function () {
        $para.text(Math.round(this.ctr));
    }
});

Since ctr represents a numeric value, we can animate it just like any other numeric property. The duration (in milliseconds) determines how long the animation will run.

The easing function applies a mathematical algorithm to alter the speed at which the animation progresses at different points within the animation. Thankfully jQuery handles the algorithm well, allowing me to keep my math skills at bay! jQuery supports linear and swing (default) easing function. We are using the linear easing function in our code.

step is a callback function that is fired at each step of the animation. This allows us to write the value of our counter to the paragraph. We are using Math.round() to round off the counter to the nearest integer. Not doing so will return the counter with decimal values and that’s not what we want.

You could use this example in a number of ways. One example is where you do a reverse count from Dec 31st to the current date and with each passing second, decrement the count to show the result as the number of seconds or minutes left, until New Year. Since handling dates in JavaScript is a mess, I would suggest you to explore a library like moment.js to do date calculations.

Live Demo

If you liked this article, take a look at my new book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!