yckart
yckart

Reputation: 33408

Change the opacity based on elements current offset

I try to set the opacity for some images, based on each current offset. The problem is, that the opacity is not equal to all images if you scroll far down.

That's what I try to accomplish, for each image:

################
#              #
#              #
#              #
#   === <= opacity 1
#              #
#   *** <= opacity 0.6
#              #
################

    ... <= opacity 0

Currently it works only for the first ~2-3 images. All further down are not set from 0-1, rather than from 0.5-40 or else.

Another problem is, that if the scroll-offset is 0, all images are hidden...

That's what I've done so far:

var $win = $(window);
var $img = $('img');

$win.on('scroll', function () {
    var scrollTop = $win.scrollTop();

    $img.each(function () {
        var $self = $(this);

        $self.css({
            opacity: scrollTop / $self.offset().top
        });
    });

}).scroll();

http://jsfiddle.net/ARTsinn/c5SUC/0/

Any ideas how to get that work?

Upvotes: 4

Views: 1281

Answers (1)

Abraham Uribe
Abraham Uribe

Reputation: 3118

you can try

var $win = $(window);
var $img = $('img');

$win.on('scroll', function () {
var scrollTop = $win.scrollTop();

$img.each(function () {
    var $self = $(this);
    var prev=$self.prev().offset();
    var pt=0;
    if(prev){
        pt=prev.top;        
    }
    $self.css({
        opacity: (scrollTop-pt)/ ($self.offset().top-pt)
    });
    console.log(scrollTop+" / "+$self.offset().top+"-"+pt);
});

}).scroll();    

http://jsfiddle.net/mQHEs/
EDIT

var $win = $(window);
var $img = $('img');

$win.on('scroll', function () {
var scrollTop = $win.scrollTop();

$img.each(function () {
    var $self = $(this);
    var prev=$self.prev().offset();
    if(prev){
        var pt=0;
        pt=prev.top;    
        $self.css({
            opacity: (scrollTop-pt)/ ($self.offset().top-pt)
        });
    }
    else{          //SHOW FIRST IMG
        $self.css({
            opacity: 1
        });
    }  
});

}).scroll();     

http://jsfiddle.net/mQHEs/1/

Upvotes: 2

Related Questions