How to draw google pie diagram only on click event using javascript / jquery?

how to draw google pie diagram only on click event using javascript / jquery?
Ive tried to call drawChart in the onclick event without success.

From 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> 
+7
jquery google-visualization onclick
source share
2 answers

To extend the response to davidkonrad, you must wrap the click event in a callback from the API loader, since it is likely that a user with a slow connection to Google servers could click the draw button before the API loading was completed:

 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"]}); 
+12
source share

Just wrap the drawchart call in 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> 
+6
source share

All Articles