Skip to content Skip to sidebar Skip to footer

How To Get Range From 0 - 1 Based On Two Number Range

In Javascript, when I am scrolling, I would like to get 0 - 1 when the scroll.x number is from 300 - 400. So 300 would be 0, then 400 would be 1, and in between would be 0.1, 0.2

Solution 1:

Yep, you'll just want a simple remapping function.

constremap = (
  value,
  sourceMin,
  sourceMax,
  destMin = 0,
  destMax = 1,
) =>
  destMin +
  ((value - sourceMin) / (sourceMax - sourceMin)) *
    (destMax - destMin);

console.log(remap(300, 300, 400));
console.log(remap(400, 300, 400));
console.log(remap(350, 300, 400));

outputs

0
1
0.5

Note that this function does not clamp the output values to the range you specify; if you specify out-of-range inputs, you'll get out-of-range outputs.

Solution 2:

You could subtract the start value and divide by 100 (the delta of the two values) for getting a value between zero and one.

functionf(x) {
    return (x - 300) / 100;
}

console.log(f(300)); // 0console.log(f(350)); // 0.5console.log(f(400)); // 1

Post a Comment for "How To Get Range From 0 - 1 Based On Two Number Range"