Ernesto Campohermoso Ernesto Campohermoso - 4 months ago 55
jQuery Question

How to add onclick event to Gauge of Google Chart?

I need to handle the onclick event over a Gauge. I don't have found an example for register events over Gauges on the Google Chart documentation.

I have tried the following:

<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart","gauge"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'LABEL');
data.addColumn('number', 'TOTAL');
data.addRows(1);
data.setValue(0, 0, 'Speed');
data.setValue(0, 1, 240);
var gaugeOptions = {min: 0, max: 280, yellowFrom: 200, yellowTo: 250, title: 'Company Performance', redFrom: 250, redTo: 280, minorTicks: 5};
var gauge = new google.visualization.Gauge(document.getElementById('gauge_div'));
gauge.draw(data, gaugeOptions);
google.visualization.events.addListener(gauge, 'select', function() {
alert("Here");
});
}
</script>
</head>
<body>
<div id="gauge_div"></div>
</body>
</html>


Also I have tried to add onclick event with JQuery to div "gauge_div" but it only works if I make click on the border of div, not over the gauge.

Answer

Gauge has no events that it triggers. The chart is rendered in an iframe, which also does not have a click event in the local dom, but rather in the window.document.body of the iframe. A solution I used was to create an empty div relatively positioned on top of the gauge and register the click event on that.

<html>
    <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("visualization", "1", {packages:["corechart","gauge"]});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = new google.visualization.DataTable();
                data.addColumn('string', 'LABEL');
                data.addColumn('number', 'TOTAL');
                data.addRows(1);
                data.setValue(0, 0, 'Speed');
                data.setValue(0, 1, 240);
                var gaugeOptions = {min: 0, max: 280, yellowFrom: 200, yellowTo: 250, title: 'Company Performance', redFrom: 250, redTo: 280, minorTicks: 5};
                var gauge = new google.visualization.Gauge(document.getElementById('gauge_div'));
                gauge.draw(data, gaugeOptions);
                google.visualization.events.addListener(gauge, 'select', function() {
                    alert("Here");
                });
            }
        </script>
    </head>
    <body style="position:relative;">
        <div id="gauge_div"></div>
        <div id="gauge_div_clickable" style="position:absolute;z-index:2;top:- 120px;width:120px;height:120px;" onclick="alert('here');">
    </body>
</html>