I am endeavoring to fix some divs in place and create a fading effect as they appear and disappear while a user scrolls down. This is what my code looks like so far:
$(window).on("load",function() {
var fadeDuration = 500;
function fade() {
// calculate current window boundaries
var windowTop = $(window).scrollTop(),
windowBottom = windowTop + $(window).innerHeight(),
focusElt = null;
// locate the focus element, which is the first visible .copy element,
// using a short-circuiting loop
$('.imgdiv').toArray().some(function(e, i) {
var objectTop = $(e).offset().top;
if ((objectTop >= windowTop) && (objectTop <= windowBottom)) {
focusElt = e;
return true;
}
console.log(focusElt);
});
// hide all other elements
$('.focus').not(focusElt)
.removeClass('focus')
.fadeTo(fadeDuration, 0);
// focus on our focus element; if it was the previous focus, leave it;
// but if it wasn't previously focused / shown, make
// it visible and assign the class 'focus'
$(focusElt).not('.focus')
.addClass('focus')
.fadeTo(fadeDuration, 1);
}
fade(); // Ensure completely visible elements are faded during page load
$(window).scroll(function() {fade();}); // Fade in elements during scroll
});
Here's a link to the corresponding fiddle that almost achieves what I'm aiming for. However, instead of the green "Fade In" blocks moving upwards and fading, I want them to stay fixed near the top of the window. As the "IMG DIVs" move past them, they should fade in and out with each new "IMG DIV". Currently, I'm focusing on the specific green block and fading it when it becomes the focus element. Instead, I need to focus on the IMG DIV blocks, add a "pinned" class to the green blocks when they reach the top of the page, and control the fading in and out of the green blocks.
Does anyone have any insights or suggestions?
As a follow-up question, I am also curious about how to achieve this using native JavaScript without relying on jQuery's dependencies.