Fixing jqPlot chart to toggle (show and hide) slices in Pie charts.

I found a question on stackoverflow where one guy found out that the enhancedLegendRenderer plugin didn’t work with jqPlot Pie Charts. He also posted a jsFiddle example where you can show/hide lines in the Line chart by clicking on legend items, but it doesn’t work with the Pie chart. I decided to investigate why it happens.

By looking at jqPlot source code I found out that the EnhancedLegendRenderer generates items 1:1 to chart series.

if (idx < series.length) {
s = series[idx];

Let’s look at the example. The Line chart with 6 lines has 6 series (series.length = 6).

The EnhancedLegendRenderer would generate only 1 item for the Pie chart. This wouldn’t look good,and jqPlot automatically disabled EnhancedLegendRenderer and applied PieLegendRenderer instead which doesn’t have much functionality.

I rewrote this renderer for Pie charts and called it EnhancedPieLegendRenderer. Here is the final result:

The link to fixed *.js files will be posted at the end of this article.
At first I created a new file, copy-pasted the code of enhancedLegendRenderer, renamed the class name, and then I replaced all “series.length” by “series[0].data.length” because as I described, Pie charts have only 1 series, but many items.
For example, I replaced the code that calculates the number of rows and columns, it looked so before:

—————
After this it started to show the legend, but the show/hide functionality didn’t work.
I decided to add a 3rd parameter to the data array which determines whether the slice is visible or not.
From

Then I replaced “handleToogle” function of EnhancedPieLegendRenderer to show/hide correctly. Here it sets the 3rd parameter above, for example, from “[‘Sony’,7,true]” to “[‘Sony’,7,false]”, and then redraws the chart: