user1517108 user1517108 - 3 days ago 5
Javascript Question

Highcharts - highlight mouse position within a range

I need to highlight mouse position when mouse is within a xAxis range of a line chart in HIighCharts.
I want to display a circle to highlight the mouse position. But I want this functionality only for the last 25 xAxis values.

Is it possible to do this in Highcharts?

One way is by following code but it has its limitations:

var circle = chart.renderer.circle(0, 0, 5).attr({
fill: 'blue',
stroke: 'black',
'stroke-width': 1
}).add()
.toFront()
.hide();

$(chart.container).mousemove(function (event) {
circle.attr({
x: event.offsetX,
y: event.offsetY
});
if (event.offsetX > SOME_VALUE) circle.show();
});


The shortcomings are that I am comparing event.offsetX instead of event.xAxis[0].value i.e. I am comparing the xValue of mouse in page rather than xAxis value in chart.

Thanks in advance

Answer

You can use point.plotX and chart.plotLeft to get position on a chart, see: http://jsfiddle.net/PNMAG/35/

Snippet:

function addCircle() {
  var chart = this;
  var circle = chart.renderer.circle(0, 0, 5).attr({
      fill: 'blue',
      stroke: 'black',
      'stroke-width': 1
    }).add()
    .toFront()
    .hide();

  $(chart.container).mousemove(function(event) {
    var normalizedEvent = chart.pointer.normalize(event);

    if (normalizedEvent.chartX > chart.series[0].data[5].plotX + chart.plotLeft) {
      circle.attr({
        x: normalizedEvent.chartX,
        y: normalizedEvent.chartY
      }).show();
    } else {
      circle.hide();
    }
  });
}
var chart = new Highcharts.Chart({
  chart: {
    renderTo: 'container',
    type: 'area',
    events: {
      load: addCircle
    }
  },
  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]
  }, {
    data: [71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 20]
  }]
});
Comments