how to draw a Google Pie Chart only on a click event using javascript/jquery?
Ive tried calling drawChart on an onclick event with no success.
From the api:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
The most common way to use Google Charts is with simple JavaScript that you embed in your web page. You load some Google Chart libraries, list the data to be charted, select options to customize your chart, and finally create a chart object with an id that you choose.
How to display both Percentage and Values in Google Pie Chart ? You can't display both on the slice labels, but if you set the pieSliceText option to 'label' and the legend. position option to 'labeled' , you will see the value on the slice and the percent on the legend label.
To extend davidkonrad's answer, you should wrap the click event in the callback from the API loader, as it is plausible that a user with a slow connection to Google's servers could click the draw button before the API is finished loading:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
function initialize () {
$(/* click event element selector */).click(function() {
drawChart();
});
}
google.setOnLoadCallback(initialize);
google.load("visualization", "1", {packages:["corechart"]});
Just wrap the call to drawchart
into a click handler instead of OnLoadCallback
:
$('html, body').click(function() {
drawChart();
});
Whole script :
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
$('html, body').click(function() {
drawChart();
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With