Dónal Dónal - 1 year ago 671
Javascript Question

zoom a Highcharts chart programatically

In this JSFiddle demo I have 2 Highcharts line charts. When one of the charts is zoomed, the other chart should zoom in on the same area. The code that does this is

xAxis: {
events: {
afterSetExtremes: function (event) {
var index = document.getElementById('container2').dataset.highchartsChart;
var chartPartner = Highcharts.charts[index];
chartPartner.xAxis[0].setExtremes(event.min, event.max);
chartPartner.showResetZoom();
}
},
},


wherein
container2
is the ID of the DOM element that the other chart is rendered to. This behaviour is almost working, but there are a couple of small problems:


  • After zooming-in, the gray shading area that is used to select the area to zoom doesn't disappear in Firefox (I haven't tested other browsers)

  • The "Reset Zoom" button doesn't appear in the other chart despite the fact that I call
    chartPartner.showResetZoom();


Answer Source

Your problem is that you called setExtremes in an infinite loop, because you told the "afterSetExtremes" event to trigger another "afterSetExtremes" event. You can prevent that easily by having a state-variable.

That's why I introduced this:

var updating = false;

and changed the last part of the events to that:

if (!updating) {
    updating = true;
    chartPartner.xAxis[0].setExtremes(event.min, event.max);
    chartPartner.showResetZoom();
}

JSFiddle: http://jsfiddle.net/qq4wnyqo/1/

Edit: The original JSFiddle even produced a console error 'maximum call stack size exceeded'. Next time you probably want to look for stuff like that.

Edit: you still need to find a solution for hiding the 'reset zoom' buttons after they're used.