Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flot graph does not render when parent container is hidden

I was having an issue where a flot graph would not render in a tabbed interface because the placeholder divs were children of divs with 'display: none'. The axes would be displayed, but no graph content.

I wrote the javascript function below as a wrapper for the plot function in order to solve this issue. It might be useful for others doing something similar.

function safePlot(placeholderDiv, data, options){

    // Move the graph place holder to the hidden loader
    // div to render
    var parentContainer = placeholderDiv.parent();
    $('#graphLoaderDiv').append(placeholderDiv);

    // Render the graph
    $.plot(placeholderDiv, data, options);

    // Move the graph back to it's original parent
    // container
    parentContainer.append(placeholderDiv);
}

Here is the CSS for the graph loader div which can be placed anywhere on the page.

#graphLoaderDiv{
    visibility: hidden;
    position: absolute;
    top: 0px;
    left: 0px;
    width: 500px;
    height: 150px;
}
like image 370
beauburrier Avatar asked Mar 25 '11 01:03

beauburrier


3 Answers

Perhaps this is better solution. It can be used as a drop in replacement for $.plot():

var fplot = function(e,data,options){
  var jqParent, jqHidden;
  if (e.offsetWidth <=0 || e.offetHeight <=0){
    // lets attempt to compensate for an ancestor with display:none
    jqParent = $(e).parent();
    jqHidden = $("<div style='visibility:hidden'></div>");
    $('body').append(jqHidden);
    jqHidden.append(e);
  }

  var plot=$.plot(e,data,options);

  // if we moved it above, lets put it back
  if (jqParent){
     jqParent.append(e);
     jqHidden.remove();
  }

  return plot;
};

Then just take your call to $.plot() and change it to fplot()

like image 82
jsd Avatar answered Sep 19 '22 13:09

jsd


The only thing that works without any CSS trick is to load the plot 1 second after like this:

$('#myTab a[href="#tabname"]').on("click", function() {
    setTimeout(function() {
       $.plot($(divChartArea), data, options);       
    }, 1000);
});

or for older jquery

$('#myTab a[href="#tabname"]').click (function() {
      setTimeout(function() {
         $.plot($(divChartArea), data, options);       
      }, 1000);
    });

The above example is applied to Bootstrap tags for Click funtion. But should work for any hidden div or object.

Working example: http://topg.org/server-desteria-factions-levels-classes-tokens-id388539 Just click the "Players" tab and you'll see the above example in action.

like image 35
Stefan Avatar answered Sep 22 '22 13:09

Stefan


This one is a FAQ:

Your #graphLoaderDiv must have a width and height, and unfortunately, invisible divs do not have them. Instead, make it visible, but set its left to -10000px. Then once you are ready to show it, just set it's left to 0px (or whatever).

like image 34
Ryley Avatar answered Sep 20 '22 13:09

Ryley