Jquery/Javascript Opacity animation with scroll

working exemple with starting and ending point here: http://jsfiddle.net/z7E9u/1/

I copy paste basic code here

    var fadeStart=100 // 100px scroll or less will equiv to 1 opacity
    ,fadeUntil=200 // 200px scroll or more will equiv to 0 opacity
    ,fading = $('#fading')
;

$(window).bind('scroll', function(){
    var offset = $(document).scrollTop()
        ,opacity=0
    ;
    if( offset<=fadeStart ){
        opacity=1;
    }else if( offset<=fadeUntil ){
        opacity=1-offset/fadeUntil;
    }
    fading.css('opacity',opacity).html(opacity);
});

Here's a working example: http://jsfiddle.net/meEf4/

And the code:

var target = $('div');
var targetHeight = target.outerHeight();

$(document).scroll(function(e){
    var scrollPercent = (targetHeight - window.scrollY) / targetHeight;
    if(scrollPercent >= 0){
        target.css('opacity', scrollPercent);
    }
});

All we do is grab the current scroll position of the window, figure out what percentage of the element in question is now off-screen, and set its opacity with that percentage.


As I have lower than 50 reputation I cannot reply to Lonut's question, how to do the reverse. Here is my code if you would like the reverse, quite handy for navigation bars.

$(window).scroll(function () {
        var offset = $(document).scrollTop()
        var opacity = 0;
        if (offset <= 0) {
            opacity = 0;
        } else if (offset > 0 & offset <= 200) {
            opacity = (offset - 1) / 200;
        }
        else {
            opacity = 1;
        }
        $('.black-background').css('opacity', opacity).html(opacity);
    });