I have a Morris JS chart trying to load within a Twitter Bootstrap tab pane. The tabs work fine, but the chart will not load.
It looks like this article discusses the problem: http://www.doidea.se/blog/morris-js-charts-in-bootstrap-tabs
How would I translate their solution into my Rails code?
Here is my code:
View:
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>
<li><a href="#profile" data-toggle="tab">Profile</a></li>
<li><a href="#messages" data-toggle="tab">Messages</a></li>
<li><a href="#settings" data-toggle="tab">Settings</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">...</div>
<div class="tab-pane" id="profile">
<%= content_tag :div, "", id: "info_chart", data: { info: @chart_data } %>
</div>
<div class="tab-pane" id="messages">...</div>
<div class="tab-pane" id="settings">...</div>
</div>
Application.JS
$('#myTab a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
ControllerName.js.coffee
$ ->
# only use morris if the post chart element is on the page.
if $('#info_chart').length > 0
Morris.Bar
element: 'info_chart'
data: $('#info_chart').data('info')
xkey: 'x'
ykeys: ['y']
labels: ['label']
Found a solution to my situation for a single chart on tabs that wasn't display properly:
Save your graph as a variable:
var usage_graph = Morris.Line({
// config
});
Then listen for changes on the tabs, and redraw the graph:
$('ul.nav a').on('shown.bs.tab', function (e) {
usage_graph.redraw();
});
I hope this helps someone else.
The top answer is partially correct. The problem, however, is the svg is not resized. In order to make sure the svg is resized, you can modify it by css:
if ($('#morris-stacked-bar-graph').length > 0) {
var morris_bar = Morris.Bar({
element: 'morris-stacked-bar-graph',
data: [
{x: '2011 Q1', y: 3, z: 2, a: 3},
{x: '2011 Q2', y: 2, z: null, a: 1},
{x: '2011 Q3', y: 0, z: 2, a: 4},
{x: '2011 Q4', y: 2, z: 4, a: 3}
],
xkey: 'x',
ykeys: ['y', 'z', 'a'],
labels: ['Y', 'Z', 'A'],
stacked: true,
barColors: $('#morris-stacked-bar-graph').data('colors').split(',')
});
$('ul.nav a').on('shown.bs.tab', function (e) {
morris_bar.redraw();
$('svg').css({ width: '100%' });
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With