Parsa Motamedi Parsa Motamedi - 25 days ago 9
jQuery Question

Javascript - Increase and decrease value based on another value

Very simply put, I have a variable

that its value ranges from 0 to 120.

What I need is a function that'll increase and decrease the opacity of another element based on the
range of 0 to 120. So if the value of
is 120, the opacity of my element becomes 0, and if its value is 0, opacity is 1. I can do this with an easy if statement, but what about all the values in between? That's my problem.

This is my code at the moment and it has only got the if statement to cover the two conditions, but not everything in between. I'm working with the sly scrollbar by the way.

var frame = new Sly('.frame', options, {
move: function() {
var posnum = frame.pos.cur //this variable's int value ranges from 0 to 120
if (posnum > 113) {$('#gradient').css('opacity', '0')}
else {$('#gradient').css('opacity', '1');}

The code works fine and runs when I want it to, but it's just the dynamic reaction that I need for the opacity to change depending on where it is in that range.

Answer Source

You can do this:

var opacity = 1 - (posnum/120);

Assuming that opacity is directly proportional to posnum.

for(var posnum = 0; posnum <= 120; posnum++) {
  var opacity = 1 - (posnum/120);
  console.log("Posnum: " + posnum, " Opacity: " + opacity);