Positioning XY Cursor via API

Sometimes you might need to programatically position your chart cursor. This tutorial will show how.

Base chart

Let's use this stacked XY chart with a Cursor pre-configured:

See the Pen amCharts: Moving chart cursor via API (1) by amCharts (@amcharts) on CodePen.24419

Placing cursor

Our reference chart has a Category axis with categories like "One", "Two", "Three", etc.

We'd like to place our cursor at, say, "Three". This means that we'll need to find out X position of the target category, then instruct the Cursor to move to that position.

And, since we want our cursor to appear on chart load, we'll also be utilizing chart's "datavalidated" event.

Getting category position

To get a position to specific category, we'll need to use our Category axis' categoryToPoint(category) method:

let point = categoryAxis.categoryToPoint("Three");
var point = categoryAxis.categoryToPoint("Three");

This function will return a simple "point" object that will have x and y properties for the specific category position.

Moving cursor to point

Now that we have position of the category, we just need to instruct our cursor to move there.

For that, we'll be using Cursor's triggerMove(point[, triggeredByPointer]) method.

chart.cursor.triggerMove(point, false);
chart.cursor.triggerMove(point, false);

Timing cursor move

Since our chart is not quite ready at the moment we're creating it, we're going to use it event to trigger cursor move:

chart.events.on("datavalidated", function(ev) {
  let point = categoryAxis.categoryToPoint("Three");
  chart.cursor.triggerMove(point, "none");
});
chart.events.on("datavalidated", function(ev) {
  var point = categoryAxis.categoryToPoint("Three");
  chart.cursor.triggerMove(point, "none");
});

If you are using animated theme, you might also delay your cursor's grand appearance until the chart has had a chance to animate itself into view:

chart.events.on("datavalidated", function(ev) {
  setTimeout(function() {
    let point = categoryAxis.categoryToPoint("Three");
    chart.cursor.triggerMove(point, "none");
  }, series1.defaultState.transitionDuration + 100);
});
chart.events.on("datavalidated", function(ev) {
  setTimeout(function() {
    var point = categoryAxis.categoryToPoint("Three");
    chart.cursor.triggerMove(point, "none");
  }, series1.defaultState.transitionDuration + 100);
});

Final result

See the Pen amCharts: Moving chart cursor via API (2) by amCharts (@amcharts) on CodePen.24419

Before you go

There's one important caveat, though.

Tooltips are hidden when their related series are being animated.

This means that if you invoke Cursor move when series is animating, which happens when "animated" theme is used and chart is loaded, no Tooltips will be shown.

So, if you are positioning the cursor on chart load, and are using "animated" theme, delay this operation by enough time.

Related tutorials