Google Chart BarChart onmouseover

旧时模样 提交于 2019-12-11 10:19:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!