When scrolling the page and arriving in a certain DIV the background color of the same changes

Asked

Viewed 181 times

2

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

Jsfiddle

but it didn’t work out. What would be the right way to do it?

Note: The website will be responsive logo scrollTop: 50px would not work!

1 answer

2


Had 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 variable aparecer which is the percentage that 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>
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 />
<div id="div" style="display: block; width: 300px; height: 200px; background: red;">
	Texto texto texto texto
</div>

  • pq trim and split by one hundred?

  • if I want to change the color again when the person goes up the page and I only for a correct LSE?

  • @Lucassimao

  • tanks now and keep it in my head

Browser other questions tagged

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