Search code examples
javascriptamcharts

amcharts: How to add an action in tooltip


I am trying to add an action in amcharts like:

function myfunc(name){
  alert("hi "+name);
}

var tooltipDetail='<div class="detail" name="{name}" onclick="myfunc({name});">detail {name}</div>'

series1.columns.template.tooltipHTML = tooltipDetail;

When I replace 'myfunc()' by 'alert(1)' it launch an alert but myfunc defined in code launch an error in console 'Uncaught ReferenceError: myfunc is not defined'. why? how can I solve this issue?

My intention was create a more elaborated function with jquery like:

$('.detail').click(function(){
  var name=this.attr("name");
  $("#selected").html(name);
});

But it does not work, then I simplify the code... I checked $('.detail').html() is not available if tooltip is not showed yet so I think it is built when tooltip is launched.

Also I tried to include the function in tooltip like:

var tooltipDetail='<script>function hi({name}){alert("hi"+name);}</script><div class="detail" name="{name}" onclick="hi({name});">detail {name}</div>'

It results in same issue, 'hi' is not defined.

Any recommendation? thanks


Solution

  • AmCharts seems to have an event system. Try using an on click event handler:

    function myfunc(){
      alert(1);
    }
    series.tooltip.events.on('hit', myFunc);
    

    See this modified CodePen where the tooltip is clickable: https://codepen.io/krassdanke/pen/ZEbyQyY (original from official amCharts docs: https://www.amcharts.com/docs/v4/tutorials/clickable-links-in-tooltips/)