Thomas.D Thomas.D - 2 months ago 11
CSS Question

JQuery "fade out" effect on scroll up

I have this code, if scroll down Fade in and show the object

css:

.fadeInBlock {
opacity:0;
}


js:

$(function() {
$(window).scroll( function(){
$('.fadeInBlock').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* Adjust the "200" to either have a delay or that the content starts fading a bit before you reach it */
bottom_of_window = bottom_of_window + 200;
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},500);
}
});

});
});


and need solution to fade out the object after scroll up.

Please advise, thank you

Answer

Maybe something like this will help

function isVisible(elem){
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function() {
  console.log('scroll')
  $('.fadeInBlock').each(function(i) {
    if (isVisible(this)) {
      $(this).animate({
        'opacity': '1'
      }, 1000);
    } else {
        $(this).css({
        'opacity': '0'
      });
    }
  });
});

https://jsfiddle.net/32feyrhy/4/