Reputation: 471
I have 3 charts in one page and I need help rendering the legends for the chart with their corresponding ones. The issue that I have is that the legends for chart 3 are showing up after chart 2 legends with chart 2, and not chart 3. What can I do to fix it?
Following are the legends that goes with chart 2:
And following are the legends that needs to go with chart 3:
With Bid
With Ask
With Bid and Ask
function set_legend() {
legend = $('#legend');
legend.html('');
let listed = {};
$.each(Highcharts.charts, function(i, chrt) {
// Flag to avoid looping through the first chart
if (i !== 0) {
$.each(chrt.series, function(j, serie) {
let tmp_key = serie.name.replace(/[\s,-]/g, '');
if (!Object.keys(listed).includes(tmp_key)) {
legend.append(
'<div class="item ' + tmp_key + '"><div class="symbol" style="background-color:' +
serie.color +
'"></div><div class="serieName" id="">' +
serie.name +
'</div></div>'
);
listed[tmp_key] = [serie];
} else {
listed[tmp_key].push(serie);
}
});
}
});
Object.keys(listed).forEach(key => {
// Get the legend and add a click handler
$('#legend .' + key).click(function() {
listed[key].forEach(serie => {
if (serie.visible) serie.setVisible(false);
else serie.setVisible(true);
});
});
});
}
For complete example, please see the following JsFiddle link: https://jsfiddle.net/samwhite/rsw47q86/5/
Upvotes: 2
Views: 176
Reputation: 17007
you have fogotten to make the difference betwwen legend and legend2:
for chart > 7 you have to select legend2 either legend:
function set_legend() {
$('div[id^=legend]').html('');
let listed = {};
var legend;
$.each(Highcharts.charts, function(i, chrt) {
// Flag to avoid looping through the first chart
if (i > 3) {
legend = i > 7 ? $("#legend2") : $("#legend");
$.each(chrt.series, function(j, serie) {
let tmp_key = serie.name.replace(/[\s,-]/g, '');
if (!Object.keys(listed).includes(tmp_key)) {
legend.append(
'<div class="item ' + tmp_key + '"><div class="symbol" style="background-color:' +
serie.color +
'"></div><div class="serieName" id="">' +
serie.name +
'</div></div>'
);
listed[tmp_key] = [serie];
} else {
listed[tmp_key].push(serie);
}
});
}
});
Object.keys(listed).forEach(key => {
// Get the legend and add a click handler
$('div[id^=legend] .' + key).click(function() {
listed[key].forEach(serie => {
if (serie.visible) serie.setVisible(false);
else serie.setVisible(true);
});
});
});
}
dont forget to modify the css rules:
#legend, #legend2 { white-space: pre; margin-top: 35px; }
Upvotes: 1