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?
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?
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(){
$(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>