Fade out div on scroll

I am fading out the div #hero-image when my page scrolls. At the moment, the code below uses a nominal value of 1000 to ensure a slow fade, but my #hero-image div is 100% the height of the browser, so I'd like the full opacity transition from 1 to 0 to happen when the user scrolls the 100% height div out of the initial viewport.

Any help much appreciated!

/* Fade #hero-image on scroll */
$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / 1000);
    });
});

Answers


Use the height of the element instead of the generic 1000 value.

Fiddle: http://jsfiddle.net/e84enbf2/

$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / $('#hero-image').height());
    });
});

If I understand your comment correctly to make the fade out complete after scrolling half the height of the div just divide by 2.

Fiddle: http://jsfiddle.net/e84enbf2/1/

$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / ($('#hero-image').height() / 2));
    });
});

Need Your Help

Smalltalk web app deployment on headless Linux server

smalltalk seaside pharo

We wrote a small prototype web app using Pharo and Seaside and we want to now demonstrate to the suits that the app can be deployed into our standard Linux build. We use a mix of CentOS, Ubuntu Ser...