4

I am currently using nvd3 for charting in my application. I have a problem in that if the div is hidden via display:none before the charts are rendered, the charts will throw an error, and upon "un-hiding" the div, I have to click on the charts to get them to render correctly. Is there any way to pre-render the charts even if the div is hidden? I have tried setting the width and height of the parent svg before calling the chart, but to no avail.

nv.addGraph(function () {
    //chart setup code

    d3.select("#chart svg").attr("width", 300).attr("height", 500);
    d3.select("#chart svg").datum(data).transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);
    return chart;
});
Wei Hao
  • 2,756
  • 9
  • 27
  • 40

3 Answers3

2

I figured out how to make a previously hidden chart render properly without needing to statically define the dimensions of the chart area:

NVD3 Charts not rendering correctly in hidden tab

This solution also depends on using JS to display the hidden content and at the same time trigger a resize event which forces NVD3 to resize the now visible chart to fill parent. In my case I didn't care about SEO so I used display:none; but visibility:hidden; would work too.

Community
  • 1
  • 1
metaColin
  • 1,973
  • 2
  • 22
  • 37
0

Just add this JavaScript:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  window.dispatchEvent(new Event('resize'));
})

hidden.bs.tab is the event that fires after a new tab is shown as per the Bootstrap docs. This code fires a resize event after each tab change.

nostromo
  • 1,435
  • 2
  • 17
  • 23
-1

You can hide a chart – but still render the graph – using a class like this:

.out-of-sight-and-space{
  visibility: hidden !important;
  position: absolute !important;
  top: 0 !important;
}

You should apply this to the parent of the svg, in your case #chart. When you want to show the chart, remove the class.

Nerian
  • 15,901
  • 13
  • 66
  • 96
  • This lacks context. For instance what element should this class be applied to? – metaColin Feb 04 '14 at 19:35
  • Also it doesn't work, I tried it both on the SVG & the parent container. – metaColin Feb 04 '14 at 20:55
  • The fix you suggest doesn't cause to chart to render correctly. It's true that it renders albeit as un unreadable overlapping mess, but unless you explicitly define the dimensions of the hidden parent div it does not pre-render in a useful way. What's more if you do define dimensions, that chart is no longer responsive. – metaColin Feb 05 '14 at 16:10