Start animation when DIV is visible

Asked

Viewed 684 times

2

I inserted some animated pizza graphics on my page, but I would like the animation to be started only when the DIV that holds these graphics was displayed on the screen, someone would know how to do this?

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.

  • I could ask the question a [mcve] demonstrating this behavior?

  • Insert the script that performs the animation, the plugin has the name of pie-Chart, this helps?

  • Which is the div with the charts?

  • When and how it becomes visible on the screen?

  • It is visible when you scroll the page to it.

  • But you want the animation to happen as soon as the div appears a little, in the middle, a little, all?

  • Ideally when she’s at least half visible.

Show 2 more comments

2 answers

1


The script below checks if a div teste (substitute teste for id of his div) is visible in the window according to the specified percentage 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>
Role para baixo
<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 />
<div id="teste">
</div>

  • My friend Dvd, perfect! Thank you very much!

-2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.