I'm using chartjs to generate a line graph with points for each element. Currently, hovering over a point on the graph triggers a tooltip for that data point. Is it possible to trigger this mouseover event (and the resulting tooltip) from elsewhere on the page? (More specifically, hovering over a row in a table should trigger the corresponding data point on the graph)
function render_graph(input) {
// setup block
const data = {
datasets: [{
type: 'line',
parsing: {
yAxisKey: 'Average Pace',
xAxisKey: 'Date',
},
label: '# of Votes',
radius: 3,
data: arr,
backgroundColor: 'red',
borderColor: 'red',
borderWidth: 1,
label: "Pace",
}]
}
// config block
const config = {
data,
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'year'
}
},
y: {
suggestedMin: 360,
suggestedMax: 900,
ticks: {
stepSize: 30,
padding: 2,
callback: function(value, index, ticks) {
minutes = Math.floor(value / 60);
seconds = value % 60;
if (seconds == 0) {
seconds = "00";
}
x = minutes + ':' + seconds;
return x;
}
},
}
},
}
};
// render / init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
return myChart;
}
You could use setActiveElements
tooltip/chart API. Here is a snippet code to show how it works.
const ctx = document.getElementById("myChart"); const myChart = new Chart(ctx, { type: 'line', data: { labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'], datasets: [{ label: 'user 1 online', data: [50, 35, 45, 47, 0, 3, 27], backgroundColor: 'rgba(40, 139, 170, 1)', borderColor: 'rgb(40, 139, 170)', pointHoverBackgroundColor: 'yellow', pointHoverRadius: 20 }] } }); document.getElementById('chart').addEventListener('click', function() { if (myChart.getActiveElements().length > 0) { myChart.setActiveElements([]); } else { myChart.setActiveElements([ { datasetIndex: 0, index: 1, }, { datasetIndex: 0, index: 3, } ]); } myChart.update(); }); document.getElementById('tooltip').addEventListener('click', function() { const tooltip = myChart.tooltip; if (tooltip.getActiveElements().length > 0) { tooltip.setActiveElements([], {x: 0, y: 0}); } else { const chartArea = myChart.chartArea; tooltip.setActiveElements([ { datasetIndex: 0, index: 1 } ], { x: (chartArea.left + chartArea.right) / 2, y: (chartArea.top + chartArea.bottom) / 2, }); } myChart.update(); });
.myChartDiv { max-width: 600px; max-height: 400px; }
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script> <html> <body> <div class="myChartDiv"> <canvas id="myChart" width="600" height="400"/> </div> <button id="chart">Chart active element</button> <button id="tooltip">Tooltip active element</button> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.