5

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

MrElephant
  • 302
  • 4
  • 26

2 Answers2

3

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

krassdanke
  • 617
  • 6
  • 24
3

@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
);
MrElephant
  • 302
  • 4
  • 26
  • Thanks for marking as best answer. It was not really clear from your initial question that you also intended to access a special data property as well. The value `name` could have been anything. Would appreciate if you could provide more information about what should be achieved in your next question :) – krassdanke Apr 28 '20 at 14:57
  • 1
    yes, you are complete right, next time I will be more verbose in my explanation. thanks dth – MrElephant Apr 28 '20 at 15:58