I have a situation where I am trying to use MorrisJS charts inside two different bootstrap tabs. The chart loads fine in the first (default) tab but when I click into the secon
Set the Morris.Bar property resize
to true:
resize: true
Assign your Morris.Bar to a variable:
var homeBar = Morris.Bar({...});
var profileBar = Morris.Bar({...});
Add an event triggered on tab change that redraws the bar chart and triggers a resize:
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
var target = $(e.target).attr("href") // activated tab
switch (target) {
case "#home":
homeBar.redraw();
$(window).trigger('resize');
break;
case "#profile":
profileBar.redraw();
$(window).trigger('resize');
break;
}
});
See full working snippet below:
var homeBar = Morris.Bar({
element: 'chart1',
data: [
{ y: '2006', a: 100, b: 90 },
{ y: '2007', a: 75, b: 65 },
{ y: '2008', a: 50, b: 40 },
{ y: '2009', a: 75, b: 65 },
{ y: '2010', a: 50, b: 40 },
{ y: '2011', a: 75, b: 65 },
{ y: '2012', a: 100, b: 90 }
],
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['Series A', 'Series B'],
hideHover: 'always',
resize: true
});
var profileBar = Morris.Bar({
element: 'chart2',
data: [
{ y: '2006', a: 100, b: 90 },
{ y: '2007', a: 75, b: 65 },
{ y: '2008', a: 50, b: 40 },
{ y: '2009', a: 75, b: 65 },
{ y: '2010', a: 50, b: 40 },
{ y: '2011', a: 75, b: 65 },
{ y: '2012', a: 100, b: 90 }
],
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['Series A', 'Series B'],
hideHover: 'always',
resize: true
});
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
var target = $(e.target).attr("href") // activated tab
switch (target) {
case "#home":
homeBar.redraw();
$(window).trigger('resize');
break;
case "#profile":
profileBar.redraw();
$(window).trigger('resize');
break;
}
});