How do I know if the browser scroll is close to the height of the div?

3

I'm trying to make the divs that are hidden at the same height (or next) as the browser scroll appear (individually) as fedeIn effect. Can anyone help me with any ideas?

    
asked by anonymous 17.01.2016 / 17:53

1 answer

4

To capture scrollTop() , use the:

var scrollTop = $('html, body').scrollTop();

To check the top of the element in question, use .offset().top , there is also the .position().top , but this captures the position relative to the parent element, as opposed to the previous one, which captures against the document:

$('#box1').offset().top 

The event you can use is .scroll() :

$(window).scroll(function(){

Example:

$(window).scroll(function(){
	var scrollTop = $('html, body').scrollTop();
  if(scrollTop >= $('#box1').offset().top){
  	$('#box1').css('background', 'red');
  }else{
  	$('#box1').css('background', '#ccc');
  }
})
div{
  width: 300px;
  height: 300px;
  background: #333;
  position: relative;
  top: 200px;
}
#box1{ background: #ccc; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="box1"></div>
<div id="box2"></div>

For the fadeIn() effect, this is applied to the element with display: none , that is, unless it has position fixed or absolute it will move the elements as they appear, and depending of your page, can cause problems. But you can change the opacity with .fadeTo () . It would look something like this:

$(window).scroll(function(){
	var scrollTop = $('html, body').scrollTop();
  if(scrollTop >= $('#box1').offset().top){
  	$('#box1').stop().fadeTo(100, 1);
  }else{
  	$('#box1').stop().fadeTo(100, 0);
  }
})
div{
  width: 300px;
  height: 300px;
  background: #333;
  position: relative;
  top: 200px;
}
#box1{ background: #ccc; opacity: 0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="box1"></div>
<div id="box2"></div>
    
17.01.2016 / 18:10