Still have questions?
Contact support

Event Listeners

Overview

In AnyChart html5 charting library, when user interacts with a chart, there's an event object generated by JavaScript that represents the user's actions. Events are distributed to the chart elements (title, legend, axis, etc.), and to make those elements respond to events, you should attach event listeners to them. Event Listeners are simply JavaScript functions once applied to an object wait for the defined action over this object to be performed. It's possible to apply more than one listener to an object. There are 5 listener methods (listen(), listenOnce(), removeAllListeners(), unlisten() and unlistenByKey()) and a lot of event types, which you can read about in this article.

Listener Types

There are five listener methods in Anychart, each type for a special case. Read the following information to find out how to use listeners.

listen()

This listener type adds an event listener to an implementing object. You can add the listen() method to an object more than once (but not to an event); each time it's added its key is returned. Look at the sample and through its code. It's necessary to define the event type and the action to perform.

chart.listen("click", function(){
	dataSet.append({
		// x value
		x: "P" + indexSetter,

		// random value from 1 to 500
		value : Math.floor((Math.random() * 500)+ 1)
	});
	indexSetter++;
});

JsFiddle Playground

listenOnce()

This listener type adds an event listener, that should react only once. It means that when the defined event happens for the first time, this listener reacts and then disables itself, so there will be no reaction when the event happens again. You can add the listenOnce() method to an object more than once; each time it's added its key is returned. It's necessary to define the event type and the action to perform to get any reaction on the event.

// adding a listener 
// click twice on any range bar to see the result

range.listenOnce("dblClick",
  function(){
    range.fill("red");
  });

JsFiddle Playground

removeAllListeners()

This listener type removes all event listeners from the object, unless you define the particular type. You can add the removeAllListeners() method to an object more than once.

// remove all listeners
chart.listen("dblClick", function(){
  chart.removeAllListeners();
});

JsFiddle Playground

Note that when you intend to stop listen to an only event or all of them, you should add an unlisten() method from inside of the listen() one.

unlisten()

This listener type disables the particular listener added using the listen() or listenOnce() methods. You can add the unlisten() method to an object more than once. The method requires the same parameters as the listener which is removing with this. To stop listen to the particular action, place an unlisten() method to the event you would like to stop listen to inside the listen() method, enabled for any action.

// create a function for what to listen and then unlisten
var func_listen = function(){
  dataSet.append({
    // x value
    x: "P" + indexSetter,

    // random value from 1 to 500
    value : Math.floor((Math.random() * 500)+ 1)
  });
  indexSetter++;
};

// add a listener
chart.listen("mouseMove", func_listen);

chart.listenOnce("click",function(){
  // adding an unlistener 
  chart.unlisten("mouseMove", func_listen);
});

JsFiddle Playground

unlistenByKey()

This listener type removes an event listener which was added with listen() by the key returned by listen() or listenOnce(). The only parameter of this method is the key to be listened to. You can use the unlistenByKey() method more than once with one object. Look at the sample and its code. It's necessary to define the key of the listener that you need to disable.

// add a listener
var key = chart.listen("mouseMove", func_listen);

// unlisten this
// click twice on the chart to see the result
chart.listen("dblclick",
  function(){
    chart.unlistenByKey(key);
  }
);

JsFiddle Playground

Event types

There are a lot of event types, which are separated to two categories: mouse-oriented and point-oriented. Types of both categories are similar to each other, the only difference is that point-oriented events contains some information about the point, while the mouse-oriented events are simple events with no point parameters. All those types you can see in the table below.

Mouse-oriented eventParametersPoint-oriented eventParameters
mouseOverAll browser paramspointMouseOverAll browser params + point params
mouseMoveAll browser paramspointMouseMoveAll browser params + point params
mouseOutAll browser paramspointMouseOutAll browser params + point params
mouseDownAll browser paramspointMouseDownAll browser params + point params
mouseUpAll browser paramspointMouseUpAll browser params + point params
clickAll browser paramspointClickAll browser params + point params
dblСlickAll browser paramspointDblСlickAll browser params + point params
drawtargetpointsHoverAll browser params + point params
boundsChangetarget, x, y, width, heightpointsSelectAll browser params + point params + array of selected points

As mentioned above, these event types provides no information about the point any event is committed on. For further information, see the example below.

//add a listener
chart.listen("mouseDown", function(){
  // this will open a new page in a new tab
  window.open("https://google.com","_blank");
});

JsFiddle Playground

Here we have made a chart that opens a new page when the mouse is pressed. Look through the next paragraph to understand the difference between the mouse-related and point-related events.

Opposite to mouse-related methods, these event types are able to tell some extra information about the point any of those events are committed on. See and explore the example below.

Here we added two listeners. One of them hears clicks and changes fill of the point, the second one hears the name of the double-clicked point, uses its "url" value as the query for google search and opens a new page with google search. When a point is clicked once, it is recolored.

// add a listener
chart.listen("pointClick", function(e){
  var index = e.iterator.getIndex();
  var row = dataSet.row(index);
  if (row.fillOld){
    row.fill = row.fillOld; delete row.fillOld;
  }else{
    row.fillOld = row.fill; row.fill = "green";
  }
  dataSet.row(index, row);
});

// add a listener
chart.listen("pointDblClick", function(e){ 
  var new_value = e.iterator.get("url");
  window.open(new_value,"_blank"); 
});

JsFiddle Playground

Manage Single Point

To make your chart more flexible, AnyChart js charting framework provides several ways of managing states of a single point. Event's parameter contains a number of properties that can ease interactivity managing.

For instance, point property can be used to get the point that triggered the event. This property provides pretty much the same options as getPoint() method does. All methods of a series point can be invoked upon this property.

As an example, let's use pointsHover event to find out the index of the hovered point and set hovered state for adjacent points.

// create chart
var chart = anychart.column();
// set series data
chart.column(data);

// create listener on point's hover event
chart.listen("pointsHover", function(event){
  // get hovered point
  var point = event.point;
  // get index of hovered point
  var index = point.getIndex();
  // get series of hovered point
  var series = point.getSeries();
  // unhover the series on point unhovering
  if (!point.hovered())return;
  // create array for further hovering
  var arrayToHover = [index];
  // checking existence of a point before hovered one
  if (series.getPoint(index-1).exists())
    // push the point for further hovering
    arrayToHover.push(index-1);
  // checking existence of a point after hovered one
  if (series.getPoint(index+1).exists())
    // push this point for further hovering
    arrayToHover.push(index+1);
  // hover points from the array
  series.hover(arrayToHover);
});

Even though this code works fine, there isn't much sense in hovering three random points. Instead, we can hover points, that are somehow related. Let's create a chart, display the income through the year and hover all the points of a quarter, the hovered point belongs to:

// event on hovering a point
chart.listen("pointsHover", function(event){
  // getter for hovered point
  var point = event.point;
  // index of hovered point
  var index = point.getIndex();
  // getter for hovered point's series
  var currentSeries = point.getSeries();
  // if this event is triggered on points unhovering, nothing will happen
  if (!event.currentPoint.hovered) return;
  // get an array of months, hovered point belong to and hover it.
  currentSeries.hover(getQuarterMonths(index));
});
// find out an array a month belong to
function getQuarterMonths(month) {
  var quarterStartMonth = 3 * Math.floor(month / 3);
  return [quarterStartMonth, quarterStartMonth + 1, quarterStartMonth + 2];
}

	var tooltip = series.tooltip();
	tooltip.titleFormat(function(point){
		var index = point.index;
		switch (true){
			case (index<3): return "First Quarter";
			case (index<6): return "Second Quarter";
			case (index<9): return "Third Quarter";
			case (index<12): return "Fourth Quarter";
		}
	});

	tooltip.format(function(point){
		var index = point.index;
		var prefix = "Income: $";
		switch (true){
			case (index<3): return prefix+sumValues([0,1,2]);
			case (index<6): return prefix+sumValues([3,4,5]);
			case (index<9): return prefix+sumValues([6,7,8]);
			case (index<12): return prefix+sumValues([9,10,11]);
		}

		function sumValues(array){
			var value = 0;
			for (var i=0;i<array.length;i++)
				value+=chart.getSeries(0).getPoint(array[i]).get("value");
			return value;
		}
	});

–> And here is a sample with these settings:

JsFiddle Playground