Adding a custom hover event to a morris.js donut chart

Morris.js is a lightweight and relatively simple JavaScript charting solution compared when compared with some of the others in the sector which have lot of options.

morrisjs-charts

However with that simplicity comes a lack of documentation.

Adding a custom hover event to donut chart

Here’s some HTML which adds a visible label element (like you get with a line chart) next to the donut chart:

<div id="morrischart" style="height: 250px; width: 250px; float: left"></div>
 <div id="morrisdetails-item" class="morris-hover morris-default-style" style="position:static; float: left;">
 <div class="morris-hover-row-label">2010 Q4</div> <div class="morris-hover-point">this is a test</div>
</div>

I won’t cover how to create the donut chart in JavaScript as you can just lift that from the morris.js examples, but you must assign the chart to a variable:

var donut = new Morris.Donut({...});

Finally the code to add hover events should look like this:

for(i = 0; i &lt; donut.segments.length; i++) {
  donut.segments[i].handlers['hover'].push(function(i){
    $('#morrisdetails-item .morris-hover-row-label').text(donut.data[i].label);
    $('#morrisdetails-item .morris-hover-point').text(donut.data[i].value);
  });
}

Here is a working example on JSFiddle.

One Reply to “Adding a custom hover event to a morris.js donut chart”

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA - answer the question below to prove you are human *