Display tooltip on PieChart slice click
Normally, tooltips on PieChart slices are shown when they are hovered by a cursor. This demo will show how we can disable this default behavior and only show tooltip when slice is tapped or clicked.
Open in:New tab
/** * --------------------------------------- * This demo was created using amCharts 4. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v4/ * --------------------------------------- */
// Create chart instancevar chart = am4core.create("chartdiv", am4charts.PieChart);
// Add datachart.data = [ { country: "Lithuania", litres: 501.9 }, { country: "Czechia", litres: 301.9 }, { country: "Ireland", litres: 201.1 }, { country: "Germany", litres: 165.8 }, { country: "Australia", litres: 139.9 }, { country: "Austria", litres: 128.3 }, { country: "UK", litres: 99 }, { country: "Belgium", litres: 60 }, { country: "The Netherlands", litres: 50 }];
// Add and configure Seriesvar pieSeries = chart.series.push(new am4charts.PieSeries());pieSeries.dataFields.value = "litres";pieSeries.dataFields.category = "country";
// Disable pulling outpieSeries.slices.template.states.getKey("active").properties.shiftRadius = 0;
// Set up slicespieSeries.slices.template.tooltipText = "";pieSeries.slices.template.alwaysShowTooltip = true;
// Add slice click eventvar currentSlice;pieSeries.slices.template.events.on("hit", function (ev) { if (currentSlice) { currentSlice.tooltip.hide(); } currentSlice = ev.target; currentSlice.tooltipText = "{category}: {value.percent.formatNumber('#.#')}% ({value.value})"; currentSlice.invalidate(); currentSlice.showTooltip();});
// Set up page click event to close open tooltipam4core.getInteraction().body.events.on("hit", function (ev) { if (currentSlice) { currentSlice.tooltip.hide(); }});<div id="chartdiv"></div>body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";}
#chartdiv { width: 100%; height: 400px;}