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?
– Lucas Simao
if I want to change the color again when the person goes up the page and I only for a correct LSE?
– Lucas Simao
@Lucassimao
– Sam
tanks now and keep it in my head
– Lucas Simao