Hi I want to know how can I make the google chart animation only start when scrolled and when it comes into view.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMultSeries);
function drawMultSeries() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population', '2000 Population'],
['New York City, NY', 8175000, 8008000],
['Los Angeles, CA', 3792000, 3694000],
['Chicago, IL', 2695000, 2896000],
['Houston, TX', 2099000, 1953000],
['Philadelphia, PA', 1526000, 1517000]
]);
var options = {
animation: {
duration: 2000,
startup: true //This is the new option
},
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
CodePudding user response:
You can add a listener on scroll and only load google chart on condition ("when the user scroll pass #chart_div") :
let alreadyLoaded = false ;
window.addEventListener('scroll', function(){
if (alreadyLoaded === false){
var element = document.querySelector('#chart_div');
var position = element.getBoundingClientRect();
if(position.top >= 0 && position.bottom <= window.innerHeight) {
// checking for partial visibility
if(position.top < window.innerHeight && position.bottom >= 0) {
alreadyLoaded = true;
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMultSeries);
function drawMultSeries() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population', '2000 Population'],
['New York City, NY', 8175000, 8008000],
['Los Angeles, CA', 3792000, 3694000],
['Chicago, IL', 2695000, 2896000],
['Houston, TX', 2099000, 1953000],
['Philadelphia, PA', 1526000, 1517000]
]);
var options = {
animation: {
duration: 2000,
startup: true //This is the new option
},
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
}
});