alxvo
alxvo

Reputation: 210

Opacity based on scroll position, cap at specific opacity

I'm using this piece of code to animate the background of my header, based on the scroll position of the window:

$(window).scroll(function() {
    var st=$(window).scrollTop();
    $('#whitebackground').animate({opacity: st / 200 },1);
});

Meaning that when scrolling more than 200px from the top, the opacity of the background div will be 1.

However, what if I want to cap this opacity range, so that it doesn't exceed 0.9 for instance?

Thank you very much in advance !

Upvotes: 2

Views: 580

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337590

You can use Math.min() to select the lowest value from a list:

$('#whitebackground').animate({ opacity: Math.min(st / 200, 0.9) }, 1);

Example fiddle

Note that the max value in the fiddle is 0.5 to make the effect more obvious.

Upvotes: 2

Related Questions