dtrinh dtrinh - 3 months ago 23
HTML Question

DIV fades onto another DIV

How would you make it if the user scrolls down a page, the top DIV fades into the DIV underneath it, and so on and so forth until it fades to a white background?

Here's a jsfiddle of my attempt: https://jsfiddle.net/fkgzzxku/

And here's it's hosted on a staging server for a better illustration: http://bound.staging.wpengine.com/

var target = $('div.slider-item');
var targetHeight = target.height();
var containerHeight = $('#intro-slider').outerHeight();

var maxScroll = containerHeight - targetHeight;
var scrollRange = (maxScroll / (target.length - 1)) + 250; // originally 450

$(document).scroll(function(e) {
var scrollY = $(window).scrollTop();
var scrollPercent = (scrollRange - scrollY % scrollRange) / scrollRange;
var divIndex = Math.floor(scrollY / scrollRange);

target.has(':lt(' + divIndex + ')').css('opacity', 0);
target.eq(divIndex).css('opacity', scrollPercent);
target.has(':gt(' + divIndex + ')').css('opacity', 1);
});


But the DIVs don't completely fade to 0, they fade to a number close to 0 so I feel like my math is wrong.
I also found that if the user scrolls too fast (by pressing page down, etc) you can see all 3 of the images faded into another.

Thanks!

Answer

I think because scrollY%scrollRange is never equal to scrollRange your scrollPercent is never 0. You can use scrollPercent= Math.round(scrollPercent*10)/10; after calculating scrollPercent to round it off to 0. Moreover the problem caused by scrolling too fast seems to be caused by the has function replacing it with slice function works fine for me ( I can't understand why ). Here is the updated code

$(document).scroll(function(e) {
var scrollY = $(window).scrollTop();
var scrollPercent =(scrollRange - scrollY % scrollRange) / scrollRange;
var divIndex = Math.floor(scrollY / scrollRange);
target.slice(0,divIndex).css('opacity', 0);
target.eq(divIndex).css('opacity', scrollPercent);
target.slice(divIndex+1).css('opacity', 1);
});

This works without rounding off scrollPercent. Hope it helps