Flot graph does not render when parent container is hidden

beauburrier picture beauburrier · Mar 25, 2011 · Viewed 7.5k times · Source

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;
}

Answer

jsd picture jsd · Nov 7, 2012

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()