How to draw a vertical line from a xAxis click event in Highcharts?

I have this following code:

Check the JS Fiddle Here

var chart = Highcharts.chart('container', {

        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            plotLines: [{
              value: 1,
              color: 'red',
              width: 2,
              zIndex: 10
            }]
        },

        series: [{
            data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }]
    });


    // the button action
    var $button = $('#button');

    $button.click(function () {
    console.log(chart.xAxis);
            var newValue = (chart.xAxis[0].options.plotLines[0].value + 1) % 12;
        chart.xAxis[0].options.plotLines[0].value = newValue;
        chart.xAxis[0].update();
    });

What I would like to do is to draw a vertical line up to xAxis which I click.

So for example, if I click on January he draws a vertical line up to January, but if i click on November he erases the line of January and draws a new line up to November.

Please, help me.

Thanks =)

Upvotes: 0

Views: 470

Answers (1)

Deep 3015
Deep 3015

Reputation: 10075

I am using chart events click function to track click and add plotLine accordingly. So click respective region for month inside chart and get plot line drawn and erase.

var chart = Highcharts.chart('container', {
  chart: {
    events: {
      click: function(e) {
        //console.log(e.xAxis[0].axis.categories[Math.round(e.xAxis[0].value)])
        chart.xAxis[0].options.plotLines[0].value = Math.round(e.xAxis[0].value);
        chart.xAxis[0].update();
      }
    }
  },

  xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    plotLines: [{
      value: 1,
      color: 'red',
      width: 2,
      zIndex: 10
    }]
  },

  series: [{
    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
  }]
});


// the button action
var $button = $('#button');

$button.click(function() {
  console.log(chart.xAxis);
  var newValue = (chart.xAxis[0].options.plotLines[0].value + 1) % 12;
  chart.xAxis[0].options.plotLines[0].value = newValue;
  chart.xAxis[0].update();
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div>
<button id="button" class="autocompare">update plot line</button>

Upvotes: 2

Related Questions