Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad flot canvas chart size within Bootstrap tab pane on initial page load

I am building a Rails 3.2.11 app with Twitter Bootstrap and Flot (also HAML and Coffeescript).

In a view, I have Bootstrap tabs implemented like so (partials are rendered in the tab panes.),

.tabbable
  %ul.nav.nav-tabs
      %li.active
        %a{'data-toggle' => 'tab', :href => '#tab1'} This is tab 1
      %li
        %a{"data-toggle" => "tab", :href => "#tab2"} This is tab 2

    .tab-content
      #tab1.tab-pane.active
        = render 'tab_one_content'
      #tab2.tab-pane
        = render 'tab_two_content'

Within a partial, I have a table. I want to render a flot chart within a td. My partial where I want to render the chart looks something like this,

  %table
    %tr
      %th
        Some heading text…
      %td
        -# Make the 12-month barchart
        - @chart_data = @barchart_12_mos_array.to_json
        #my_barchart.barchart{:data => {:bardata => @chart_data}}

I am applying the chart dimensions with a CSS class like this,

.barchart {
  width: 240px;
  height: 120px;
}

My Coffeescript looks like this. I expect the chart to plot on document.ready

$ ->
  $.plot $('#my_barchart'), [
    data: $("#my_barchart").data("bardata")
    bars:
      show: true
      barWidth: (365/12)*24*60*60*1000*.75
      align: 'center'
  ],
    xaxis:
      mode: "time"
      timeformat: "%b"
      monthNames: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]
    yaxis:
      position: 'right'

I have confirmed this .js is loading.

The Problem:

When the DOM initially loads, the chart renders, but it is the wrong size. The chart area (where the bars are only) is as set with the .barchart CSS, but the axes labels, etc. are outside that dimension (see http://i36.tinypic.com/2vte1rp.jpg, red dashes are border of td).

Upon refresh (I have .js that refreshes to the previously selected tab), the chart renders in the correct size I want (i.e., the axes labels are inside the dimension, see http://i38.tinypic.com/4qq15g.jpg ).

I think I have to get the correct placeholder dimensions to Flot, but don't know how. Adding width/height CSS to the td does not fix the problem. Any ideas?

like image 640
Peter Bloom Avatar asked Apr 21 '13 23:04

Peter Bloom


1 Answers

It sounds like the placeholder is within an element that starts out hidden. jQuery has trouble obtaining dimensions of hidden elements, which is a common cause of mis-sized plots. If that's the case, try showing the element before calling $.plot (you can position it absolutely, offscreen, to avoid any flickering), then reset it afterwards.

like image 161
DNS Avatar answered Oct 08 '22 12:10

DNS