mheavers mheavers - 1 year ago 134
Javascript Question

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

In other programming languages such as processing, there is a function which allows you to convert a number that falls within a range of numbers into a number within a different range. What I want to do is convert the mouse's X coordinate into a range between, say, 0 and 15. So the browser's window dimensions, while different for every user, might be, say, 1394px wide, and the current X coordinate might be 563px, and I want to convert that to the range of 0 to 15.

I'm hoping to find a function of jquery and javascript that has this ability built in. I can figure out the math to do this by myself, but I'd rather do this in a more concise and dynamic way.

I'm already capturing the screen dimensions and mouse dimensions with this code:

var $window = $(window);
var $document = $(document);

$document.ready(function() {
var mouseX, mouseY; //capture current mouse coordinates
var screenW, screenH; //capture the current width and height of the window
var maxMove = 10;

$document.mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;


$window.resize(function() {

function windowSize(){
screenW = $window.width();
screenH = $window.height();


Thanks for any help you can provide.

Answer Source

If you'd like to have access to this in the Number class, you can add it as… = function (in_min, in_max, out_min, out_max) {
  return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

…wherein you specify in the "minimum" and "maximum" values of expected input and the "minimum" and "maximum" values to be output. This can and will produce out-of-range values if the incoming value itself is not between in_min and in_max.

Use it like this:

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

Edit: I've made this available as a Gist, so you don't have to look this up, in the future.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download