When scrolling the page and arriving at a certain DIV the background color of the same one changed

2

I would like when someone scrolls the page and arrive at a certain DIV the background color of the same changed I tried to do so:

JsFiddle

But it did not work. What would be the right way to do it?

Note: The site will be responsive soon scrollTop: 50px would not work!

    
asked by anonymous 08.01.2018 / 16:28

1 answer

2

I've already answered similar question here .

To do this, you have to calculate the distance of the element to the top of the document minus the scroll, and subtract by the visible height of the window.

I added a aparecer variable that is the percentage where the element is visible in the window to change the background color:

$(window).on("scroll",function(){
	var aparecer = 50; // porcentagem (neste caso, é a metade, 50%)
	var eleHeight = $('#div').outerHeight(); // altura da div
	var eleTopo = $('#div').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))) {
		$("#div").css("background","blue");
	}
});
<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/><divid="div" style="display: block; width: 300px; height: 200px; background: red;">
	Texto texto texto texto
</div>
    
08.01.2018 / 16:46