Rock Rock - 7 months ago 192
Javascript Question

Render to same Container with multiple chart types and options

Depending the selected chart type (line/column/scatter, etc), is it possible to have multiple option settings in one single render? For instance I have two chart types:

var options = {
chart: {
renderTo: 'container',
type: 'column',
},
title: {
text: title
},
subtitle: {
text: subtitle
},
xAxis: {
categories: []
},
yAxis: {
min: 0,
title: {
text: 'Percentage'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function () {
return Math.round(this.y * 100) + '%';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: []
};


And:

var options = {
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: title
},
subtitle: {
text: subtitle
},
xAxis: {
categories: []
},
yAxis: {
min: 0,
title: {
text: 'Count'
}
},
tooltip: {
formatter: function () {
var s = '';

$.each(this.points, function (i, point) {
s += point.series.name + ': ' + point.y + '<br/>';
});
return s;
},
shared: true
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
};


Is it possible to combine them together as in one
$(document).on("click", ".render-Chart", function () {...}
or
var chart
? Thank you!

Answer

I didn't really get the question. But if the question is, "Is it possible?" Then why don't you directly try doing it. If you have tried and it did not turn out as expected, get back here with a jsFiddle tryout and your expected vs actual behaviors.

If what you are asking is if you have two charting options one for line and another for column, both pointing to the same container, and based on some click or condition you would either want to plot a line or column, but not both then yes very much possible. If you are afraid that you have mentioned the same container id in both the options causing some conflict then, make a note that the options by themselves are just variables that store data/info and don't modify the DOM or execute themselves, it's only the Highchart's constructor that takes these as parameter and plots the chart, so as long as the constructor is called only once, you should be safe using the same container n number of times, or the latest constructor's chart would be plotted to that container.

var lineOptions = {
    chart: {
        type: 'line',
        renderTo: 'container',
        //...
    }
    //...
};

var columnOptions = {
    chart: {
        type: 'column',
        renderTo: 'container',
        //...
    }
    //...
};
//...
var chart;
function onClick(){
    if(...){
        chart = new Highcharts.StockChart(lineOptions);
    }else if(...){
        chart = new Highcharts.StockChart(columnOptions);
    }       
}