currently I am trying to create a page where individual fixed images fade in and out as you scroll. Above the images is text. Fading in while scrolling down works very well so far, but unfortunately fading out doesn't look so nice. This is because I have arranged the images with Position: sticky and they are only shown when they are 100% in the viewport. By scrolling up this works just fine, but scrolling down you can see the upper edge of the image while it is moving out of view.
Unfortunately I'm not a javascript professional and I can't find the page where I found the code i'm currently using. Otherwise I would have looked there again or linked it here.
It would be great if it would be enough to extend the javascript code.
This is what it looks like now: https://codepen.io/nejou/pen/yLvggoe
This is the script:
(function(){
function hasClass(el, cls) {
if (el.className.match('(?:^|\\s)'+cls+'(?!\\S)')) { return true; }
}
function addClass(el, cls) {
if (!el.className.match('(?:^|\\s)'+cls+'(?!\\S)')){ el.className += ' '+cls; }
}
function delClass(el, cls) {
el.className = el.className.replace(new RegExp('(?:^|\\s)'+cls+'(?!\\S)'),'');
}
function elementFromTop(elem, classToAdd, distanceFromTop, unit) {
var winY = window.innerHeight || document.documentElement.clientHeight,
distTop = elem.getBoundingClientRect().top,
distPercent = Math.round((distTop / winY) * 100),
distPixels = Math.round(distTop),
distUnit;
distUnit = unit == 'percent' ? distPercent : distPixels;
if (distUnit <= distanceFromTop) {
if (!hasClass(elem, classToAdd)) { addClass(elem, classToAdd); }
} else {
delClass(elem, classToAdd);
}
}
// params: element id, class to add, distance from top, unit ('percent' or 'pixels')
window.addEventListener('scroll', function() {
elementFromTop(document.getElementById('fade-background-01'), 'active', 0, 'pixels');
}, false);
window.addEventListener('scroll', function() {
elementFromTop(document.getElementById('fade-background-02'), 'active', 0, 'pixels');
}, false);
window.addEventListener('scroll', function() {
elementFromTop(document.getElementById('fade-background-03'), 'active', 0, 'pixels');
}, false);
window.addEventListener('scroll', function() {
elementFromTop(document.getElementById('fade-background-04'), 'active', 0, 'pixels');
}, false);
})();
Thanks in advance