I tried to trigger the tooltip for a specific entry in a google chart when coming from a link from an external URL.
The tooltip should show with the following URL: https://example.com/page?showTooltip=Identifier
The data point in the chart is selected, but the tooltip doesn’t show. The trigger for the tooltip is set to "both". Any ideas on how to fix this?
const urlParams = new URLSearchParams(window.location.search);
const showTooltip = urlParams.get('showTooltip');
if (showTooltip) {
google.visualization.events.addListener(scatterChart, 'ready', function() {
setTimeout(() => {
showTooltipForEntry(showTooltip);
}, 1000);
});
}
function showTooltipForEntry(entryName) {
const rowIndex = data.getFilteredRows([{
column: 1,
value: entryName
}])[0];
if (rowIndex === undefined) return; // If no matching row, exit
scatterChart.getChart().setSelection([{
row: rowIndex,
column: null
}]);
}
2
Answers
If the ready has already triggered, then it will not work
You need to move it to just before you create the chart
If I’m not wrong, you may be trying to implement this in Vanilla Javascript, Here’s a reliable way to achieve this, even if the default tooltip behavior doesn’t trigger consistently:
Explanation
Chart Instance: Pass the
chart
instance to theshowTooltipForEntry
function to ensure you’re working with the correct chart and data, especially if you have multiple charts.ready
Event: This event is crucial because it ensures the tooltip triggering logic runs only after the chart is fully loaded and ready to interact with.Filtering and Selection: The code finds the relevant data point using
getFilteredRows
and then selects it usingchart.setSelection
. This prepares the chart to display the tooltip.Force Tooltip Display: This is the key part. We explicitly call
tooltip.draw()
to force the tooltip to appear. This is necessary because relying solely on the "trigger" option may not always work as expected, especially when navigating from an external URL.Additional Considerations
Error Handling: The
if (rowIndex !== undefined)
check prevents errors if the specified entry doesn’t exist.URL Parameter: Make sure your external URLs are structured like this:
https://example.com/page?showTooltip=Identifier
.Customization: You can customize the tooltip’s content by modifying what’s passed to
tooltip.draw()
.