Search code examples
javascriptmobilehighchartszooming

Highchart on mobile (Touch to zoom out and zoom in) - LineChart


I'm trying to apply ZoomIn and ZoomOut in a line chart on a mobile device. The goal is to click on a zone of the chart and ZoomIn in the first click and ZoomOut on the second. The sequence will always be this one.

I already live to see the documentation / examples and I can not find anything to solve this situation.

I have already tried using this properties in the chart: property

pinchType : 'y',
zoomType: 'none'

I tried the zoomtype but the behavior is not what I expect. I want to have a click to zoom this specific area of ​​the chart. I do not want to zoom with two fingers.

{
    chart: {
        pinchType : 'x'
    },
    legend: {
        itemStyle: {
            color: '#fff'
        }
    },
    plotOptions: {
        series: {
            animation: {
                duration: 2000
            }
        }
    },
    xAxis: {
        tickInterval: 1
    },
    series: [
        {
            type: 'spline',
            color : '#fff'
        },
        {
            dashStyle: 'longdash',
            color: '#b3be77'
        }
    ],
}

As simple as clicking to get zoomin and zoomout


Solution

  • Yes, the second challenge can be easily achieved by adding this logic to plotOptions.series.events.click callback function:

      chart: {
        events: {
          load: function() {
            this.clickedOnce = false;
          },
          click: function() {
            const chart = this;
    
            if (chart.clickedOnce) {
                chart.zoomOut();
              chart.clickedOnce = false;
            }
          }
        }
      },
      plotOptions: {
        series: {
          events: {
            click: function(e) {
              const chart = this.chart,
                yAxis = chart.yAxis[0],
                xAxis = chart.xAxis[0];
    
              let x,
                y,
                rangeX,
                rangeY;
    
              if (!chart.clickedOnce) {
                x = xAxis.toValue(e.chartX);
                y = yAxis.toValue(e.chartY);
                rangeX = xAxis.max - xAxis.min;
                rangeY = yAxis.max - yAxis.min;
    
                xAxis.setExtremes(x - rangeX / 10, x + rangeX / 10, false);
                yAxis.setExtremes(y - rangeY / 10, y + rangeY / 10, false);
                chart.redraw();
    
                chart.clickedOnce = true;
              } else {
                chart.zoomOut();
                chart.clickedOnce = false;
              }
            }
          }
        }
      }
    

    Demos: