Currently in the process of developing a web app at , I am looking to implement a feature that will fade elements in and out as they enter and leave the visible part of a scrolling parent element. Taking inspiration from myfunkyside's response on this post Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window, I have incorporated a similar code snippet found here https://jsfiddle.net/tciprop/u4vaodvL/. However, I seem to be facing issues where either the offset top of the elements is too large or the visible area of the scrolling div is positioned too low, causing the fade effect to overlap into the visible region. Any insights or suggestions are welcome. Here is the link to my Fiddle: https://jsfiddle.net/tciprop/u4vaodvL/.
HTML
<div class="header"></div>
<div class="menu">
<div class="fade">Fade In 01</div>
<div class="fade">Fade In 02</div>
<div class="fade">Fade In 03</div>
<div class="fade">Fade In 04</div>
<div class="fade">Fade In 05</div>
<div class="fade">Fade In 06</div>
<div class="fade">Fade In 07</div>
<div class="fade">Fade In 08</div>
<div class="fade">Fade In 09</div>
<div class="fade">Fade In 10</div>
<div class="fade">Fade In 01</div>
<div class="fade">Fade In 02</div>
<div class="fade">Fade In 03</div>
<div class="fade">Fade In 04</div>
<div class="fade">Fade In 05</div>
<div class="fade">Fade In 06</div>
<div class="fade">Fade In 07</div>
<div class="fade">Fade In 08</div>
<div class="fade">Fade In 09</div>
<div class="fade">Fade In 10</div>
</div>
CSS
body {
overflow-x: hidden;
overflow-y: hidden;
}
.header {
height: 40px;
}
.fade {
position: relative;
margin: 10px 5px 10px 5px;
padding: 10px 5px 10px 5px;
background-color: lightgreen;
opacity: 1;
height: 50px;
}
.menu {
position: relative;
overflow-x: hidden;
overflow-y: scroll;
border: 2vw 3vh;
width: 90vw;
height: 80vh;
margin: auto;
}
JS
$(window).on("load",function() {
$(".menu").scroll(function() {
$(".fade").each(function() {
//find relative positions
var objectTop = $(this).offset().top;
var objectBottom = objectTop + $(this).outerHeight();
var windowTop = $(".menu").scrollTop();
var windowBottom = windowTop + $(".menu").innerHeight();
if (objectTop < windowTop) {//fade out on leaving top of scrollable area
if ($(this).css("opacity")==1) {
$(this).fadeTo(500,0);
}
} else if (objectBottom < windowBottom && objectTop > windowTop) {//fade in on entering top of scrollable area
if ($(this).css("opacity")==0) {
$(this).fadeTo(500,1);
}
} else if (objectBottom < windowBottom) {//fade in on entering bottom of scrollable area
if ($(this).css("opacity")==0) {
$(this).fadeTo(500,1);
}
} else {
if ($(this).css("opacity")==1) {//fade out on leaving bottom of scrollable area
$(this).fadeTo(500,0);
}
}
console.log(objectTop, objectBottom, windowTop, windowBottom);
});
}); $(".menu").scroll(); //invoke scroll-handler on page-load
});