Search code examples
javascriptamcharts

Click event for label in amCharts


I am working on amCharts Donut chart.

Following is the script for creating the chart.

JS

var chart = AmCharts.makeChart( "chartdiv", {
  "type": "pie",
  "pullOutDuration":0.5,
 "pullOutRadius": "5",
 "theme": "light",
 "dataProvider": [ {
   "title": "Aaa",
   "value": 10,
 }, {
   "title": "Bbb",
   "value": 10,
 },{
   "title":"Ccc",
   "value":10,
 },{
   "title":"Ddd",
   "value":10,
 },{
   "title":"Eee",
   "value":10,
 }],
 "titleField": "title",
 "valueField": "value",
 "labelRadius": 50,

 "radius": "35%",
 "innerRadius": "85%",
 "labelText": "[[title]]",
 "export": {
   "enabled": true
 },
 "baseColor":"#7a4436",
 "pullOutOnlyOne":true,
 "startEffect":"easeOutSine",
 "pullOutEffect":"easeOutSine",
 "showBalloon":false,
 "listeners": [{
     "event": "clickSlice",
     "method": function(e) {
          var dp = e.dataItem.dataContext;
          alert(dp.title + ':'+dp.value)

          e.chart.validateData();
     }
   }]
});

enter image description here

I am able to give click event listener for each slice of the chart.

But I would like to add a click event for label of each slice. So here in my example click event for the labels Aaa, Bbb, etc..

Edit

or how to give an anchor tag to these Labels??

Here is the working fiddle demo


Solution

  • Normally the listener for clickSlice is only attached to the wedge and the little tick to the label, but not to the label itself.

    You can do this manually though, using this code piece:

    chart.addListener("init", function() {
        var d = chart.chartData;
        for (var i = 0; i < d.length; i++) {
            d[i].label.node.style.pointerEvents = "auto";
            chart.addEventListeners(d[i].labelSet, d[i]);
        }
    });
    

    As the labels have the pointer-events style assigned to none automatically, you have to change this back, so the mouse-events can be registered. Then you can add a listener manually to the svg element using a method provided by the chart.

    You have to do this after the chart was initialized. However if you want to remain the e.chart.validateData() call in your handler, you have to listen on a different event (like drawn).

    If the purpose of e.chart.validateData() was to stop a slice to be pulled out, the better way to do this would be using pullOutRadius: 0

    Here's a demo.