Reputation:
I have multiple sections on a page. Each has an overlay that starts out at 1
opacity. I would like it to reduce opacity as you scroll with it reaching 0
when the bottom of the element is at the top of the page.
I based this code on another question here, and it almost works for one, but I want to do this for multiple elements on the page and that's where things break down. When I try it, each subsequent element starts out less opaque and it's even worse if the window size is reduced.
$(window).scroll(function () {
var homeTop = $(window).scrollTop();
var height = $(window).height() / 2;
$('#splashback-home').css({
'opacity': ((height - homeTop) / height)
});
});
How can I make this dynamic for say any element with the .splashback
class?
I'm thinking something like this?
$('.splashback').each(function () {
var scrollTop = $(window).scrollTop();
var thisTop = $(this).offset().top;
var thisHeight = $(this).height();
newOpacity = ???
if (newOpacity > 1) newOpacity = 1;
$(this).css({'opacity': newOpacity});
});
Upvotes: 2
Views: 2976
Reputation: 5389
You're close - you need to take the element's offset into account for each .splashback
:
$(window).scroll(function() {
var homeTop = $(window).scrollTop();
$(".splashback").each(function() {
var height = $(this).height();
var offset = $(this).offset().top;
var opacity = (height - homeTop + offset) / height;
$(this).css("opacity", opacity);
});
});
div {
background: red;
height: 1000px;
margin-bottom: 100px;
}
.splashback {
background: lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Some div (will not fade)</div>
<div class="splashback">Some div splashback 1</div>
<div class="splashback">Some div splashback 2</div>
<div>Some div (will not fade)</div>
Upvotes: 6