Detect scroll when start and end of div with jquery

0

Well, I need to detect when scrolling the page (regardless of whether it is the mouse scroll or browser sidebar) to go through a particular div to identify the beginning and end of it, since I need to apply an animation when the scrolling is going through she. Does anyone have an idea of where to start at least?

    
asked by anonymous 14.09.2018 / 01:07

1 answer

2

You can detect it by scrolling when the div appears completely in the window (see explanations in the code itself). I used as an example div with class .mdiv , there you change according to the class, id or other selector you are using.

$(window).on("scroll", function(){ // dispara o evento scroll da janela
   
   var div_heigh = $(".mdiv").height(); // pega a altura da div
   var win_heigh = window.innerHeight; // pega a altura da janela
   var win_scrol = $(this).scrollTop(); // pega o valor da rolagem da janela
   var div_topo  = $(".mdiv").offset().top; // distância da div até o início do documento
   var distancia = div_topo - win_scrol - win_heigh; // distância da div até a borda inferior da janela
   
   // se a distância da altura da div à borda inferior da janela for menor ou igual a 0
   if(distancia <= -div_heigh){
      $(this).off("scroll"); // cancelo o evento "scroll" para não entrar novamente no "if"
      console.log("a div apareceu toda!");
   }
   
});
.esp{
   height: 500px;
   background: yellow;
}

.mdiv{
   height: 200px;
   background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="esp">Role para baixo</div>
<div class="mdiv">Minha div</div>
<div class="esp">Espaçador</div>
    
14.09.2018 / 01:52