Zooming Flot Chart by jQuery Slider

June 4, 2011

I have a jQuery slider with double drag handles to control a date range. When the slider is moved, a table is filtered down to rows matching the range on the slider. I wanted to extend this to change a flot chart to show the same date range.

jQueryUI Slider

The slider simply filters by a class name on the table rows (This is a Django template with dynamic values):

$("#slider-range").slider({
    range: true,
    min: {{FirstResultYear}},
    max: {{LastResultYear}},
    values: [ {{FirstResultYear}}, {{LastResultYear}} ],
    slide: function( event, ui ) {
        $("#slider-amount").html(ui.values[0] + " - " + ui.values[1]);
        for (var i={{FirstResultYear}};i<={{LastResultYear}};i++){
            $('.year-' + i).show();
            if (i < ui.values[0]) {
                $('.year-' + i).hide();
            }
            if (i > ui.values[1]) {
                $('.year-' + i).hide();
            }
        }
    }
});

Flot Chart

In order to filter the chart, we need to pass in the required date range.

Previously, the chart was created using:

plot = $.plot($("#flot_chart"), lFlotData, lFlotOptions);

To filter the chart, we add more code to the slide event. This code simply calculates the date range required, then re-plots the chart with xaxis limited to the range required.

var lFromDate = new Date(ui.values[0] + '/1/1');
var lToDate = new Date(ui.values[1] + '/12/31');
plot = $.plot($("#flot_chart"), lFlotData, $.extend(true, {}, lFlotOptions, {
    xaxis: { min: lFromDate, max: lToDate }
}));

References