Reputation: 1600
I am currently fading in divs upon sacroll but within one of the sections I have a chart which animates but it animates when the page loads currently. What I need it to do is fire when you scroll to it on the page. Here is my current js:
JS CODE
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll( function(){
/* Check the location of each desired element */
$('.hideme').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},500);
}
});
});
Chart.defaults.global.animationEasing = 'easeInOutQuad',
Chart.defaults.global.responsive = true;
Chart.defaults.global.scaleOverride = true;
Chart.defaults.global.scaleShowLabels = false;
Chart.defaults.global.scaleSteps = 10;
Chart.defaults.global.scaleStepWidth = 10;
Chart.defaults.global.scaleStartValue = 0;
Chart.defaults.global.tooltipFontFamily = 'Open Sans';
Chart.defaults.global.tooltipFillColor = '#FFFFFF';
Chart.defaults.global.tooltipFontColor = '#6E6E6E';
Chart.defaults.global.tooltipCaretSize = 0;
Chart.defaults.global.maintainAspectRatio = true;
Chart.defaults.Line.scaleShowHorizontalLines = false;
Chart.defaults.Line.scaleShowHorizontalLines = false;
Chart.defaults.Line.scaleGridLineColor = '#fff';
Chart.defaults.Line.scaleLineColor = '#eee';
var chart = document.getElementById('chart').getContext('2d'),
gradient = chart.createLinearGradient(0, 0, 0, 0);
var data = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June'],
datasets: [{
label: 'Custom Label Name',
fillColor: gradient,
strokeColor: '#41AAE3',
pointColor: '#41AAE3',
pointStrokeColor: 'rgba(220,220,220,1)',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data: [5, 12, 28, 37, 60, 100]
}]
};
gradient.addColorStop(0, 'rgba(255, 0,0, 0.5)');
gradient.addColorStop(0.5, 'rgba(255, 0, 0, 0.25)');
gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
var chart = new Chart(chart).Line(data);
});
Upvotes: 1
Views: 323
Reputation: 206151
Wrap your chart code into a function
var chartIsShown = false;
// .....
function chartInit() {
chartIsShown = true;
// chart code here
}
than inside the each function inside the "if is visible" if
add another if
:
if(this.id==="chartCanvasContainer" && chartIsShown===false) { // Add this
chartInit();
}
$(this).animate({'opacity':'1'},500); // before this.
where id="chartCanvasContainer"
is the ID assigned to the hideme
parent of your #chart
canvas:
<div class="hideme">Lorem ipsum</div>
<div class="hideme" id="chartCanvasContainer"> <!-- assign the ID! -->
<canvas id="chart"></canvas>
</div>
<div class="hideme">foo bar ofc</div>
<!-- .etc. -->
Upvotes: 1