How to resize Morris.js chart on changes to container dimensions

sonya picture sonya · Feb 18, 2016 · Viewed 10.8k times · Source

I try to put Morris js donut chart in the flex container with 2 flex items, I expect that chart in flex: 1 container will resize, but it does not. Does anyone know how to make the chart to be responsive in flex item?

Here is my example example try to resize it

JS:

$(function () {
    Morris.Donut({
        element: 'container',
        resize: true,
        data: [
            {label: "Download Sales", value: 12},
            {label: "In-Store Sales", value: 30},
            {label: "Mail-Order Sales", value: 20}
        ]
    });

CSS:

html, body {
height: 100%;
margin: 0;
}

body {
    display: -webkit-flex;
}

#container {
  flex: 1;
}

.flex1 {
  flex: 1;
  border: 1px solid red;
}

Answer

thedarklord47 picture thedarklord47 · Feb 18, 2016

Add a $(window).on('resize', ...) event handler then call the graphs redraw() function.

If there is a dynamic UI element that causes the layout to "flex" based on user input, you will want to call redraw() there as well as there is no way to directly listen for the resizing of a div.

Here is your fiddle, updated with the fix.

jsFiddle

Also, here is a note from a developer of Morris.js

Note: I suggest you call redraw() sparingly as it's quite an expensive operation. Try using a setTimeout trick or similar to avoid calling it for intermediate resize events.

A way to heed this advice is below:

$(window).on('resize', function() {
   if (!window.recentResize) {
      window.m.redraw();
      window.recentResize = true;
      setTimeout(function(){ window.recentResize = false; }, 200);
   }
});

Here is a fiddle with this implemented:

jsFiddle