Multiple Series underneath and get clicked y- value and x-value

Viewed 13

Someone had a problem here: Highcharts.js - Event when any point is clicked_ They found a good solution. i have the same problem, but i have multiple y-series underneath. how can i detect which series was the correct one to be clicked?

example here:

// create the chart
Highcharts.chart('container', {
    chart: {
    type: 'line',
        events: {
            click: function (event) {
                var label = this.renderer.label(
                    'x: ' + Highcharts.numberFormat(event.xAxis[0].value, 2) + ', y: ' + Highcharts.numberFormat(event.yAxis[0].value, 2),
                    event.xAxis[0].axis.toPixels(event.xAxis[0].value),
                    event.yAxis[0].axis.toPixels(event.yAxis[0].value)
                )
                    .attr({
                        fill: Highcharts.getOptions().colors[0],
                        padding: 10,
                        r: 5,
                        zIndex: 8
                    })
                    .css({
                        color: '#FFFFFF'
                    })
                    .add();

                setTimeout(function () {
                    label.fadeOut();
                }, 1000);
            }
        }
    },

      yAxis: [{ min: 1, max: 3,
      height: '40%'},{
      height: '60%', top: '40%'}],
    series: [{
    yAxis: 0,
        data: [2,2,2,2,2,2,2,2]
    },
    {
    yAxis: 1,
        data: [2.9, 3.5, 106.4, 129.2, 1.0, 4.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
});
1 Answers

You can find the proper yAxis by comparing min and max with event values. For example:

  chart: {
    events: {
      click: function(event) {
        const yAxis = event.yAxis.find(axis => (
          axis.axis.max >= axis.value && axis.axis.min <= axis.value
        ));

        if (!yAxis) {
          return;
        }

        const label = this.renderer.label(
            'x: ' + Highcharts.numberFormat(event.xAxis[0].value, 2) + ', y: ' + Highcharts.numberFormat(yAxis.value, 2),
            event.xAxis[0].axis.toPixels(event.xAxis[0].value),
            yAxis.axis.toPixels(yAxis.value)
          )
          .attr({
            fill: Highcharts.getOptions().colors[0],
            padding: 10,
            r: 5,
            zIndex: 8
          })
          .css({
            color: '#FFFFFF'
          })
          .add();

        setTimeout(function() {
          label.fadeOut();
        }, 1000);
      }
    }
  }

Live demo: https://jsfiddle.net/BlackLabel/yfq9t2jd/

API Reference: https://api.highcharts.com/highcharts/yAxis

Related