I would like to have div
elements fade in and out when scrolling over them by changing the opacity. It sounds really simple but can’t get it to work.
The problem I have is that the div
are in the middle of my page and not on top, so scrollTop
shouldn’t work 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>
(JsFiddle)
2
Answers
You can use the Intersection Observer API. It watches for changes in the intersection between a target element and its ancestor element or the viewport.
First, create a new observer with options:
root
specifies either the ancestor (containing) element, e.g. withdocument.querySelector()
, or the viewport withnull
.threshold
can take an array of intersection thresholds to watch for, which we’ll directly use as opacity for our elements. So each time an element’s intersection ratio with the viewport reaches one of these values, the callback is triggered. (You can use a function here to build the array if you want a more fine-grained sequence and don’t want to write everything by hand.)Next, add each element to the observer:
The callback is very simple, as we can directly use the provided
intersectionRatio
as opacity.entries
is an array of all watched elements that you can loop through:So much to get you started. Go read the documentation, it’s excellent and has many examples.
Probably not the best but here is my try :
On scroll, I check the position of every element to see wich one is the most centered
On window resize, I update the center of screen value