progresspieSVG

jQuery plug-in for dynamically rendering a pie or circle diagram comparable to a progress bar, depicting a progress, countdown, percent value or similar.

Project home page

What is this?

This software module contains a jQuery plug-in for drawing a partially filled circle (pie-chart with only one slice of the pie) for visualizing a single value between 0% and 100% inclusive, i.e. a kind of progress bar, but not in form of a bar but of a pie. The graphic is rendered inside a web page as SVG. In difference to e.g. the HTML canvas element, SVGs are scalable and render sharply on high resolution displays with device-pixel-ratio > 1 (e.g. Apple’s “retina displays”).

As the name suggests, this component may be used to display a progress, starting at 0%, incrementing until 100% are reached. For this purpose the graphic may be dynamically updated (or, more precisely, replaced).

But just like progress bars these pies may actually be used to depict any percentual value, including static ones like e.g. percents of points achieved in a test. Mainly for this purpose, the pie may be dynamically colored based on the percentual value with colors like red hinting at a “bad” result, yellow for “mediocre” and green for “good”. There are default color schemes (always grey, green or red or dynamically calculated red/yellow/gree-shade as described above), but you may also assign any static color or your own JavaScript function mapping the value into a color.

Examples

See the examples pages to get an impression of the looks and for different demo scenarios.

You’ll also find an online live view of these examples on the project’s home page.

JavaScripts

This package contains 5 JavaScript files (sources in folder js and minified production versions in js/min):

Usage

Direct usage of the plug-in (without progresspiesvgAppl.js)

Basics

Options

If you simply call progressPie(), the plug-in will be used with default options. This includes that the percent number is expected to be the (only) content of the selected element, the pie will be prependet to this content (separated with an  ), it will be rendered in line-height and in a shade of grey (#888). It will only be inserted, if the element does not yet contain any SVG content: repetetive calling of the function will therefore neither insert the SVG multiple times nor will it update the graphic.

To modify the looks or behaviour, the function takes exactly one argument, which has to be a JavaScript object which defines options via its properties. The following option properties are defined:

Dynamically updating pies

Overwriting default options

Writing your own color function

As described above, by simply setting the option {mode: $.fn.progressPie.Mode.COLOR}, the color of the pie get dynamically calculated based on the percent value, and the colors used for that are in some degree customizable via overwriting $.fn.progressPie.Mode.GREEN.value or …RED.value.

But if you want more flexibility in dynamically setting a color, you may provide your own JavaScript function which receives the percent value as parameter (number) and has to return a string describing the color (like #3bf or rgb(100,255,100)).

You could simply overwrite the function $.fn.progressPie.colorByPercent. This way your function would always be applied for any pie rendered in COLOR mode.

But the more flexible way is to write one or more own color functions and apply them individually to (classes of) pies instead of using the default COLOR mode, which is then still available.

Simply write your function and then set a reference to it in the options passed to the options, like in:

<script type="text/javascript">
function blueGt25(percent) {
  var blue = percent < 25 ? 0 : (percent-25)*3; //range from 0 to 3*75 = 225 ( = max brightness for value of 100%)
  return "rgb(0,0," + blue + ")";
}

$(function() {
  $(".test.myblue").progressPie({color:blueGt25});
});
</script>

The example above defines a color function which sets the pie color to black for all values of 0% to 25% inclusive. For values greater than 25% the color is blue: an rgb code with red and green values of 0 and a blue component growing brighter with the percent value up to 225 (a little darker than the brightest blue (255)).

Of course, a color function may also be embedded inline in the options object, if it’s not needed elsewhere. The following example defines an inline function setting one (greenish) color for values starting at 50% and another color (reddish) for lower values:

$(".test.myfunc").progressPie({color:function(percent) {
  return percent >= 50 ? "#3f3" : "#f33";
}});

Last but not least you may reuse the internal color function $.fn.progressPie.colorByPercent within your own color function instead of calculating a color code all by yourself: Let’s say, you want all values between 0% and 50% to be drawn in the same red and apply the default COLOR scheme only for values starting at 50% (green for 100%, yellow for 75%, red for 50%). This could be done the following way:

function colorGt50(percent) {
  var p = percent <= 50 ? 0 : 2 * (percent - 50);
  return $.fn.progressPie.colorByPercent(p);
}

valueAdapters and double pies

If the source value to be visualized as filled circle (pie) is not a percent value (0..100), you may write your own adapter function for mapping the actual values (any string) to a percent number. This mapping might be of arithmetic nature (e.g. converting a value of 0 to 60 minutes into a percent number) or of syntactic nature (e.g. extracting a percent number out of a string also containing other characters)—or both. Use the valueAdapter option (see above) to specify your adapter function. (Default is parseInt, i.e. a function simply interpeting a string like “100” as a (decimal integer) number.

If you want to display two values in one graphic (e.g. hours and minutes), that’s also possible—not as simple to read/understand at first glance, though. Use the inner option (see above) to specify that and how the second, inner pie should be generated.

The examples page examples.html contains demonstrations for both options.

Note: These features are only available with direct use of jquery-progresspiessvg.js and not via progresspiesvgAppl.js.

Simplified usage via progresspiesvgAppl.js

If you prefer not to write your own JavaScript-/jQuery-Code in order to apply the progresspie plug-in to selected elements of your choice, you may use this additional JavaScript file. It is a default application of the plug-ins to elements which must meet some conventions.

If you include this script into an HTML document, each HTML element of class progresspie is fitted with a pie chart. This requires the element (which is usually an inline element like a span) to contain a number from 0 to 100 (inclusive) as its only content or alternatively in an attribute named data-percent.

By default the pie is grey. By adding an additional class color, red or green you get a dynamically colored resp. statically red or green pie. (These classes must not be combined and activate the corresponding plug-in mode COLOR, RED or GREEN respectively.)
Adding the class vcenter activates vertical centering, otherwise the graphic is aligned with the bottom of the element.

For user-defined color you may either add an attribute data-piecolor defining a static color code or an attribute data-piecolor-function providung a string which evaluates to a function mapping a number (range 0..100) to a color code.

SVG Content plug-ins

The progresspieSVG jQuery plug-in provides a private plug-in mechanism itself, which may be used to plug additional drawing logic into the main plug-in, adding SVG content to the pie or ring chart.

To apply a content plugin, add the option contentPlugin to the argument object you pass to the jQuery plug-in. The value of this option is either a reference to a javascript function (conforming to the plug-in API as described below), or simply the name of a function as a string. In the latter case the function must be member of the namespace jQuery.fn.progressPie.contentPlugin. Only then it can be looked up by its name. This is the recommended namespace for any content plug-in.

A content plug-in may itself be configured by an object defining options. Any properties defined in an object passed to the jQuery progress pie plug-in via its option contentPluginOptions will be passed along to the content plug-in specified by contentPlugin.

Control Icons

jquery-progresspiesvg-controlIcons.js is a script file defining three such content plug-ins play, stop and pause for drawing media control icons (a right-pointing triange, square or two parallel vertical rectangles, resp.) inside a ring graph.

By default, the play-, pause or stop icon is drawn in the same color as the pie/ring chart itself. If combined with a ring chart (i.e. option ringWidth is set, see above), it is auto-sized to fit inside the ring, otherwise it’s drawn on top of the pie and auto-sized to fit into the outer circle stroke. These defaults may be overridden by the following options (defined as properties of an object assigned to the contentPluginOptions option):

See the content plug-ins example page for demonstrations of the plug-in and its options.

Check if complete

jquery-progresspiesvg-checkComplete.js is a script file defining a single content plug-in (checkComplete). This plug-in will draw a check mark onto a fully filled pie or into a fully closed ring (i.e. on a graph visualizing a 100% value). It won’t add any content for lower values.

See the content plug-ins example page for demonstrations of the plug-in and its options.

Value Display

jquery-progresspiesvg-valueDisplay.js is a script file defining content plug-ins for drawing a value inside a ring graph.

This script defines two content plug-ins: percent and rawValue. Both are designed to be combined with ring charts (i.e. usage of the progressPie plug-in with the ringWidth option set) and draw a number (value) and optionally a unit label into the ring. The percent plug-in always renders a percent value (0..100).

If the chart is defined with other than percent values and a valueAdapter function is used to convert the raw value to a percent value, then the percent plug-in will render the result of the valueAdapter function, while the rawValue plug-in will draw the unconverted, raw value. The percent plug-in always adds the label “%” to the value, while the rawVale plug-in takes a unit argument defining an optional label to append to the value.

The plug-ins accept the following options (defined via contentPluginOptions):

Instead of passing an individual options object to the progressPie plugin via its contentPluginOptions option, you may also globally alter the defaults by manipulating the object $.fn.progressPie.contentPlugin.valueDisplayDefaults.

See the content plug-ins example page for demonstrations of the plug-in and its options.

Writing your own content plug-ins (API)

You may create you own content plug-in function:

The function should be in the namespace jQuery.fn.progressPie.contentPlugin. If it is, you may simply state the function’s name as a string literal in the contentPlugin option. (Otherwise the options needs to hold a JavaScript function reference to the content plug-in function.)

Just like when writing jQuery plug-ins, you may locally bind the $ sybol to jQuery in an immediately invoked function expression like:

( function($) {
    $.fn.progressPie.contentPlugin.yourPluginFunction = function(args) {
        …
    }
} (jQuery));

Your function has to take exactly one argument (let’s assume you call the formal parameter args like in the example above). When your plug-in function gets called by progressPie, this parameter will hold an object with at least the following properties:

In addition to these properties, the args object will hold any property the user added to the contentPluginOptions object. If your plug-in should define its own properties (such as the fontSizeFactor option of the Value Display content plug-in described above), simply document these and the user of your content plug-in may insert these options into the contentPluginOptions.

After evaluating these arguments, your function may now insert SVG elements (using the newSvgElement function and maybe also newSvgSubelement). For positioning these elements, you need to know the origin of the coordinate system: The point (0, 0) refers to the center of the circle!

As a very simple example, the following function describes a content plug-in which simply draws a filled square inside the ring graph (or on top of a pie graph) in the same color and with a side length which equals the radius of the circle. So, since (0, 0) is the circle’s center and the square should be circled and radius is the width and height of the square, its top left corner has to be located at the coordinates (-radius/2, -radius/2):

( function($) {
    $.fn.progressPie.contentPlugin.mySquare = function(args) {
        var square = args.newSvgElement("rect");
        var topleft = - args.radius / 2;
        square.setAttribute("x", topleft);
        square.setAttribute("y", topleft);
        square.setAttribute("width", args.radius);
        square.setAttribute("height", args.radius);
        square.setAttribute("style", "fill: " + args.color + "; stroke: none");
    }
} (jQuery));

Have a look at the source code of the included content plug-ins for more examples.

License: BSD 2-clause

Copyright (c) 2015, Immo Schulz-Gerlach, www.isg-software.de
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.