问题
I am trying to add an listener on a "onmouseover" event on a Google BarChart, but cannot get it to work. I want to use the "mouseover"-element to make a ajax call...(a snippet of my code):
dataTable = google.visualization.arrayToDataTable(dataRaw, false);
var chart = new google.visualization.BarChart(document.getElementById("successChart"));
//Setting options for the chart
var options = {}....;
chart.draw(dataTable, options);
// Add actionlistener
google.visualization.events.addListener(chart, 'select', selectHandler);
google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);
function onmouseoverHandler() {
var selectedItem = chartGennemført.getSelection()[0]; // gets the value the vAxis
}
The "select" handler is working fine (not shown in code), but not "onmouseover". How do I add the onmouseoverHandler ...Any suggestions ?
回答1:
event listeners need to be added to the chart before the chart is drawn
also, the 'onmouseover'
event will pass the row and column as arguments to the listener function
and, getSelection
returns an array, both when a chart element is selected and unselected,
need to check the length of the array before trying to access the contents...
this will fail when a bar is unselected
getSelection()[0]
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var dataRaw = [
['x', 'y'],
[0, 0],
[1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5]
];
dataTable = google.visualization.arrayToDataTable(dataRaw, false);
var chart = new google.visualization.BarChart(document.getElementById("successChart"));
var options = {};
// Add actionlistener
google.visualization.events.addListener(chart, 'select', selectHandler);
google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);
chart.draw(dataTable, options);
function onmouseoverHandler(properties) {
console.log(JSON.stringify(properties));
}
function selectHandler() {
var selectedItem = chart.getSelection();
if (selectedItem.length > 0) {
console.log(JSON.stringify(selectedItem[0]));
} else {
console.log('nothing selected');
}
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="successChart"></div>
来源:https://stackoverflow.com/questions/51748143/google-chart-barchart-onmouseover