I'm trying to achieve a fade-in and fade-out effect on div
elements when scrolling over them by adjusting their opacity. However, I'm facing difficulties in getting it to work properly.
The issue lies in the fact that my div
elements are positioned in the middle of the page rather than at the top, so using scrollTop
doesn't seem to be the right approach, right?
var fade = $('.b_wrapper');
var range = 400;
$(window).on('scroll', function() {
var st = $(this).scrollTop();
fade.each(function() {
var offset = $(this).offset().top;
var height = $(this).outerHeight();
offset = offset + height / 1;
$(this).css({
'opacity': 1 - (st + offset - range) / range
});
});
});
.content {
height: 100px;
}
.b_wrapper {
background: lightgreen;
margin-top: 40px;
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div class="content"></div>
<div class="b_wrapper">
<p>this is a div</p>
</div>
<div class="b_wrapper">
<p>this is a div</p>
</div>
<div class="b_wrapper">
<p>this is a div</p>
</div>
<div class="b_wrapper">
<p>this is a div</p>
</div>
<div class="b_wrapper">
<p>this is a div</p>
</div>
<div class="b_wrapper">
<p>this is a div</p>
</div>
<div class="b_wrapper">
<p>this is a div</p>
</div>