highcharts: fire animation when visible instead of on page load
animation, highcharts
Solution
Attach a scroll event listener to the window that detects when you get close to the `skills` section. When you create the chart, remove the scroll listener to ensure that the chart is only created once. This will also help with performance: no reason to listen to an event that we aren't going to respond to anymore.
This approach also works if the user clicks the `skills` link at the top.
You want to be careful with the scroll event as it can be a real performance bottleneck. I took the approach suggested by John Resig to check the scroll position at regular intervals.
Working Demo
$(function () {
var $window = $(window),
didScroll = false,
skillsTop = $('#skills').offset().top - 40; //the point at which we will create the chart
$window.on('scroll', function () {
//detected a scroll event, you want to minimize the code here because this event can be thrown A LOT!
didScroll = true;
});
//check every 250ms if user has scrolled to the skills section
setInterval(function () {
if (didScroll) {
didScroll = false;
if ($window.scrollTop() >= skillsTop) {
createChart();
}
}
}, 250);
function createChart() {
$window.off('scroll'); //remove listener that will create chart, this ensures the chart will be created only once
$('#container').highcharts({
//chart configuration here
});
};
});
Problem
i have a page separated out into sections that are accessed via anchors. is there a way to have the highcharts animation fire when its particular section becomes visible instead of on page load? http://jsfiddle.net/YFMSb/2/ (the chart is under 'skills', so would like its initial animation to occur when that section of the page is brought up. does not need to re-animate during subsequent visits to/through the section) ``` $(function () { $('#container').highcharts({ chart: { type: 'bar', spacingTop: 0 }, title: { text: '' }, xAxis: { labels: { enabled: false } }, yAxis: { min: 0, max: 100, title: { text: '' }, labels: { enabled: false } }, plotOptions: { series: { stacking: 'normal' } }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b>'; } }, series: [{ name: 'clean', data: [10], }, { name: 'eat', data: [10] }, { name: 'sleep', data: [40] }, { name: 'work', data: [30] }, { name: 'play', data: [10] }] }); }); ```