Start animation when the DIV is visible

2

I inserted some animated pie charts on my page, but I wish the animation was only started when the DIV that contains these graphics was displayed on the screen, would anyone know how to do it?

The following animation should be started when the DIV with the graphics is visible:

$('#pie-one,#pie-two,#pie-tree').pieChart({
        barColor: '#21d927',
        trackColor: '#eee',
        lineCap: 'square',
        lineWidth: 18,
        onStep: function (from, to, percent) {
            $(this.element).find('.pie-value').text(Math.round(percent) + '%');
        }
    });

Thank you.

    
asked by anonymous 31.10.2017 / 22:00

2 answers

1

The script below checks whether div teste (replace teste with id with div ) is visible in the window according to the percentage specified and calls the action:

$(window).on("scroll load",function(){
	var aparecer = 50; // porcentagem (neste caso, é a metade, 50%)
	var eleHeight = $('#teste').outerHeight(); // altura da div
	var eleTopo = $('#teste').offset().top; // distancia da div ao topo do documento
	var scrlTopo = $(window).scrollTop(); // quanto foi rolada a janela
	var distance = eleTopo-scrlTopo; // distancia da div ao topo da janela
	var altJanela = window.innerHeight; // altura da janela

	if(distance <= altJanela-(eleHeight*(aparecer/100))) {
		$("#teste").html("div visível"); // só para exemplo, pode apagar esta linha e descomentar as linhas abaixo
//		$('#pie-one,#pie-two,#pie-tree').pieChart({
//			barColor: '#21d927',
//			trackColor: '#eee',
//			lineCap: 'square',
//			lineWidth: 18,
//			onStep: function (from, to, percent) {
//				$(this.element).find('.pie-value').text(Math.round(percent) + '%');
//			}
//		});
	}
});
#teste{
	display: block; width: 300px; height: 100px; background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Roleparabaixo<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><divid="teste">
</div>
    
31.10.2017 / 23:18
-1

Try to put your code inside a block like this:

$( window ).on( "load", function() {
 //Seu código 

});

Source: link

    
31.10.2017 / 22:53