- tags::
- source:: echarts lock tooltip after click
To lock or “pin” a tooltip in place after a click in Apache ECharts, you must disable the default hover-based mousemove show/hide rules and manually trigger the tooltip using a click event listener and the dispatchAction API.
Here is the functional setup to achieve this:
The Solution
- Set the tooltip
triggerOnproperty to'none'so it doesn’t disappear on hover. - Add a
clickchart event listener that captures the exact data point. - Use the
dispatchActionmethod to programmatically pin the tooltip at those coordinates. i
Example Code
// 1. Initialize ECharts instance
var myChart = echarts.init(document.getElementById('main'));
// 2. Set the configuration options
myChart.setOption({
tooltip: {
triggerOn: 'none', // Disable default mouse movement behavior
formatter: function (params) {
return 'Series: ' + params.seriesName + '<br/>Value: ' + params.value;
}
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
name: 'Sales',
type: 'line',
data: [150, 230, 224, 218, 135, 147, 260]
}]
});
// 3. Lock/Pin tooltip on click
myChart.on('click', function (params) {
// Show the tooltip at the clicked data point's position
myChart.dispatchAction({
type: 'showTip',
seriesIndex: params.seriesIndex,
dataIndex: params.dataIndex
});
});Use code with caution.
Unlocking the Tooltip
If you want to unpin or hide the tooltip when the user clicks again, you can expand the click event listener with a toggle check using the hideTip action:
let isPinned = false;
myChart.on('click', function (params) {
if (isPinned) {
// Unlock/Hide tip
myChart.dispatchAction({ type: 'hideTip' });
isPinned = false;
} else {
// Lock/Show tip
myChart.dispatchAction({
type: 'showTip',
seriesIndex: params.seriesIndex,
dataIndex: params.dataIndex
});
isPinned = true;
}
});Use code with caution.
For more advanced interaction patterns like dragging, see the Apache ECharts Drag Interaction Guide.