Search code examples
tooltiplegendtruncateamcharts4

amCharts 4: display legend tooltip on truncated (with ellipsis) values only


I've enabled the legend on a amCharts v4 chart with the following code but I have issues with ellipsis:

// Add legend
chart.legend = new am4charts.Legend();
chart.legend.fontSize = 11;

// Truncate long labels (more than 160px)
chart.legend.labels.template.maxWidth = 160;
chart.legend.labels.template.truncate = true;
chart.legend.labels.template.fullWords = true;

// Set custom ellipsis as default one is not displayed correctly
chart.legend.labels.template.ellipsis = "...";

// Set tooltip content to name field
chart.legend.itemContainers.template.tooltipText = "{name}";

As you can see I had to set a custom ellipsis property because Firefox v76 displayed €| instead of on the truncated legend labels. It happens even on the sample on the amChart website but, surprisingly, not if I open the same URL in a private tab... How can I fix that?

Then I would like to display the tooltip on the legend only for truncated labels. Adding an adapter:

chart.legend.itemContainers.template.adapter.add("tooltipText", function(text, target) {
     // 'text' here contains the non-truncated string
    return "My modified " + text;
})

of course works, but how can I identify inside the adapter code if the label that I'm processing is truncated and clear the text variable? It doesn't make sense to display tooltips for non-truncated legend items.


Solution

  • I found the answer about the tooltip adapter; this works:

    chart.legend.itemContainers.template.adapter.add("tooltipText", function(text, target) {
         if (!target.dataItem.label.isOversized) {
              // Legend label is NOT truncated, disable the tooltip
              return "";
         }
    
         // Legend label is truncated, display the tooltip
         return text;
    })
    

    Still I don't know why the ellipsis are not displayed correctly without setting the property...