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

Asked

Viewed 1,909 times

3

I am trying to make the Divs that are hidden when they are at the same height (or near) of the browser scroll appear (individually) as fedeIn effect. Can someone help me with some idea?

1 answer

5

To capture the scrollTop(), use the:

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

To verify the top of the element in question, use the .offset().top, there is also the .position().top, but this captures the position in relation to the parent element, unlike the previous one, which captures in relation to the document:

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

The event that can be used is the .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>
<div id="box1"></div>
<div id="box2"></div>

In relation to the effect fadeIn(), this is applied to the element with the display: none that is, unless you are with the position fixed or absolute this will move the elements when they appear, and depending on your page, may give problems. But you can change the opacity with the .fade(). 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>
<div id="box1"></div>
<div id="box2"></div>

Browser other questions tagged

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