Martin Štěpán Martin Štěpán - 3 months ago 29
jQuery Question

NS_ERROR_FAILURE in Firefox when drawing dimple.js chart after jquery

I'm triing to draw a dimple.js svg bar chart, which is nested in jquery-ui tabs and accordeon, which I use for my website layout and I get pretty desperate. Everything works fine in Chrome and IE, but FF keeps throwing NS_ERROR_FAILURE exception. Here is the code snippet:

function drawDimpleChart(){
d3.json("synkon-dat.php", function (data) {
var svg = dimple.newSvg("#graph-txttypy-d3", 590, 400);
var myChart = new dimple.chart(svg, data);
myChart.setBounds(100, 70, 480, 150);
myChart.addPctAxis("x", "ratio");
myChart.addCategoryAxis("y", "kategorie");
myChart.addSeries("varianta", dimple.plot.bar);
myChart.addLegend(200, 10, 380, 20, "right");
myChart.draw();
});
}

$(document).ready(function() {
$("#tabs").tabs();
$(".accordion").accordion({ active: 'none', clearStyle: true });
drawDimpleChart();
});


I've realized that the issue is related to the order in which jquery and the drawing function are executed. When I call jquery in the callback after the .draw method, everything works, but I realy need the tabs to show before all the data comes back (this can take some time).

Please help, what do I miss?

Answer

Here's a jsFiddle to replicate the problem based on the simple example from the dimple home page (in this example chart is on tab 2):

function drawDimpleChart(){
    var svg = dimple.newSvg("#tabs-2", 800, 600);
    var data = [
        { "Word":"Hello", "Awesomeness":2000 },
        { "Word":"World", "Awesomeness":3000 }
    ];
    var chart = new dimple.chart(svg, data);
    chart.addCategoryAxis("x", "Word");
    chart.addMeasureAxis("y", "Awesomeness");
    chart.addSeries(null, dimple.plot.bar);
    chart.draw();
}

$(document).ready(function() { 
    $("#tabs").tabs();
    drawDimpleChart();
});

http://jsfiddle.net/VGwGc/5/

The problem is related to the issue here:

https://github.com/PMSI-AlignAlytics/dimple/issues/34

Dimple does a lot of measuring on the SVG and this isn't possible when the div (and therefore the svg) is hidden. In browsers other than firefox, label alignment goes wrong, but firefox throws the NS_ERROR_FAILURE error.

The solution is to draw to a visible div and immediately move it into the hidden div when drawing completes. You can see it working in this fiddle:

function drawDimpleChart(){
    var svg = dimple.newSvg("#chartTab", 600, 400);
    var data = [
        { "Word":"Hello", "Awesomeness":2000 },
        { "Word":"World", "Awesomeness":3000 }
    ];
    var chart = new dimple.chart(svg, data);
    chart.addCategoryAxis("x", "Word");
    chart.addMeasureAxis("y", "Awesomeness");
    chart.addSeries(null, dimple.plot.bar);
    chart.draw();
    $("#chartTab").appendTo("#tabs-2");
}

$(document).ready(function() { 
    $("#tabs").tabs();
    drawDimpleChart();
});

http://jsfiddle.net/VGwGc/4/

I hope this helps.

John