Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 696
MrElephant Avatar asked Apr 25 '20 08:04

MrElephant


2 Answers

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/)

like image 129
krassdanke Avatar answered Sep 27 '22 15:09

krassdanke


@dth was in good way, the complete answer would be:

function myFunction(name){
  alert(name);
};

series1.columns.template.events.on(
  "hit",
  ev => {myFunction(ev.target._dataItem.dataContext["name"]);},
  this
);
like image 45
MrElephant Avatar answered Sep 27 '22 16:09

MrElephant