My attempt at changing the opacity of text blocks based on the scroll position is not functioning properly. The goal is to fade in each text block as it comes into view and fade out when it goes out of view while scrolling.
You can see an example of what I mean on this website here - look for the features section.
screenshot showing the referenced section: https://i.sstatic.net/eBP9i.png
$(window).scroll(function() {
var scrollTop = $(this).scrollTop();
$('.text-block').each(function () {
$(this).css({
opacity: function() {
var elementHeight = $(this).height(),
opacity = ((elementHeight - scrollTop) / elementHeight);
return opacity;
}
});
});
});
h1 {
height: 100vh;
background: red;
text-align: center;
}
.text-block {
width: 50%;
margin-bottom: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>SCROLL DOWN</h1>
<div class="text-block">
Content of the first text block.
</div>
<div class="text-block">
Content of the second text block.
</div>
<div class="text-block">
Content of the third text block.
</div>
<div class="text-block">
Content of the fourth text block.
</div>