Equalizing Ranges with JavaScript

Occasionally you’ll run into a problem where you have two or more ranges that you need to equalize. This is probably most common when charting or using graphs but also comes in to play when using things like HTML5 range sliders¬†where you need to make a dynamic slider that has a range from 0 – 12 equalize to 0 – 100.

Taking the range slider example, let’s say we’re trying to capture how many hours a day something is in use. That means we would likely have a minimum value of 0 and a maximum value of 24.

The Problem

If we want to position something along the slider as it updates we would need to know it’s relative position, but we can’t just do a simple percentage because 0-24 is a very different range than 0-100.

So how do we find a relative position of the current value of the slider?

Enter Linear Equations (Point-Slope)

We’re going to be using the Point-Slope Form to find our relative location.

y - y1 = m(x - x1)

Where m is the slope of the line and


is any point on the line.

The first thing we need to do is solve for m because we already know x and y (our range values values).

To solve for m we would convert the Point-Slope form to the following:

m = y - y1 / (x - x1)

After that we need to multiply the slope by the current value.

Pseudo Code

This is a reduced example assuming you’re equalizing to a percentage.

var findSlope = function(min, max) {

    var x = [min, max];
    var y = [0, 1];
    return (y[1] - y[0]) / (x[1] - x[0]);

var findRelativePosition = function(val) {

    var slope = findSlope(0, 24);
    var min = 0;
    var max = 24;
    // We need to use (val - min) in the event our minimum value isn't 0. For example, if we want to use 12-24 as our hourly range.
    return slope * (val - min) * 100;

findRelativePosition(12); // 50
findRelativePosition(13); // 54.16
findRelativePosition(24); // 100

Leave a Reply

Your email address will not be published.