Javascript / jQuery - map a range of numbers to another range of numbers

You can implement this as a pure Javascript function:

function scale (number, inMin, inMax, outMin, outMax) {
    return (number - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}

Use the function, like this:

const num = 5;
console.log(scale(num, 0, 10, -50, 50)); // 0
console.log(scale(num, -20, 0, -100, 100)); // 150

I'm using scale for the function name, because map is frequently associated with iterating over arrays and objects.


If your range always starts from 0 then all you have to do is

mouseValue * range.max / screen.max

A more involved any-range to any-range conversion would require

function convertToRange(value, srcRange, dstRange){
  // value is outside source range return
  if (value < srcRange[0] || value > srcRange[1]){
    return NaN; 
  }

  var srcMax = srcRange[1] - srcRange[0],
      dstMax = dstRange[1] - dstRange[0],
      adjValue = value - srcRange[0];

  return (adjValue * dstMax / srcMax) + dstRange[0];

}

Use like convertToRange(20,[10,50],[5,10]);


For a general purpose mapping function, which is what the OP asked for, go here:

http://rosettacode.org/wiki/Map_range#JavaScript


This is simple math.

var screenWidth = $(window).width();
var mousePosition = e.pageX;
var max = 15;
var value = (mousePosition / screenWidth) * max;

Note that this can return a decimal number; if you don't want that, you can use Math.round on the result.

Live example


function proportion(value,max,minrange,maxrange) {
    return Math.round(((max-value)/(max))*(maxrange-minrange))+minrange;
}

In your case, use this as proportion(screencoord,screensize,0,15)

You'd also presumably want to get the Client size, not the screen size, as the Screen size refers to the maximum dimensions of the monitor, and not all users maximise their screen.