Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Morris JS Chart Not Loading in Twitter Bootstrap Tab Pane

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']
like image 564
user2270029 Avatar asked Mar 01 '14 01:03

user2270029


2 Answers

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.

like image 140
tmartin314 Avatar answered Sep 20 '22 14:09

tmartin314


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%' });
        });
    }
like image 40
Daniel Viglione Avatar answered Sep 20 '22 14:09

Daniel Viglione