Search code examples
javascriptjquerymorris.js

Trigger a click event on donut segment in morris.js


I am able to keep a default segment in donut using Morris.select().

Apart from this I want to trigger a click event on the same (segment of default selection). Is there a way to attain this?

I even tried $('path').eq(1).trigger('click'), but it didn't work.


Solution

  • Add a on('click') function in your Morris Donut object. Then you can access the Donut data with the row parameter.

    As you said, you can select a segment with the select(index) method of the Donut. Then if you want to display the data of the corresponding segment, call a function that takes the Donut data as parameter, ex: morrisDonut.data[index].

    Here is a working example:

    var morrisDonut = Morris.Donut({
      element: 'donut',
      data: [
        {label: "Download Sales", value: 12},
        {label: "In-Store Sales", value: 30},
        {label: "Mail-Order Sales", value: 20}
      ],
      resize: true
    }).on('click', function (i, row) {  
        // Do your actions
        // Example:
        displayData(i, row);
    });
    
    // Index of element to select
    var i = 2;
    // Selects the element in the Donut
    morrisDonut.select(i);
    // Display the corresponding data
    displayData(i, morrisDonut.data[i]);
    
    function displayData(i, row) {
        $('#data').html(row.label + ": " + row.value);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
    <link href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css" rel="stylesheet" />
    
    <div id="donut"></div>
    <div id="data"></div>