Wednesday, September 2, 2015

Morris Donut Charts place inside Bootstrap Tabs

While I was working with Morris Donut charts I faced a problem when placing this charts inside many tabs. It works in one page but not in tabs. So, here is the solution.

When placing Morris Donut Chart inside tabs we should call redraw() function. Chart/s in first tab will alright without calling redraw() function but for other tabs JS is not working properly without calling redraw().

Here is the code...
Download morris.js from following link
http://morrisjs.github.io/morris.js/


<!DOCTYPE html>
<html>
<head>
            <link href=".../morris.css" rel="stylesheet">
</head>
<body>

<!-- put below divs inside each Bootstrap nav-tabs -->

<div id="donut-snapshot"></div>
<div id="donut-style"></div>
<div id="donut-order"></div>

<script src=".../jquery-ui.min.js"></script>
<script src=".../raphael-min.js"></script>
<script src=".../morris.js"></script>

<!-- 1st tab chart - no need redraw()-->
<script>
    Morris.Donut({
        element: 'donut-snapshot',                               //js calls inside this id
        colors : ["#EC407A","#2196F3","#8BC34A","#AB47BC"],     //set colors for each bar
        resize : true,
        data   : [
            {label: "Completed", value: 52},
            {label: "Pending", value: 30},
            {label: "Delay", value: 20},
            {label: "Due", value: 20}
        ]
    });
</script>

<!-- 2nd tab chart - now call redraw()-->
<script>
    var graphStyle = Morris.Donut({
        element: 'donut-style',
        data: [
            {label: "Completed", value: 12},
            {label: "Pending", value: 30},
            {label: "Delay", value: 20},
            {label: "Due", value: 20}
        ],
        colors: ["#EC407A","#2196F3","#8BC34A","#AB47BC"],
         
    });
        $('ul.nav a').on('shown.bs.tab', function (e) {
            graphStyle.redraw();
    });
 
</script>

<!-- 3rd tab chart - again call redraw() -->
<script>
    var graphOrder = Morris.Donut({
        element: 'donut-order',
        data: [
            {label: "Completed", value: 12},
            {label: "Pending", value: 30},
            {label: "Delay", value: 40},
            {label: "Due", value: 20}
        ],
        colors: ["#EC407A","#2196F3","#8BC34A","#AB47BC"],
         
    });
        $('ul.nav a').on('shown.bs.tab', function (e) {
            graphOrder.redraw();
    });
 
</script>

</body>
</html>


                                                                        1st tab

2nd tab

3rd tab