Skip to content

Instantly share code, notes, and snippets.

@alana314
Created April 10, 2017 23:07
Show Gist options
  • Save alana314/7a832604714af7043dd619b499185a3d to your computer and use it in GitHub Desktop.
Save alana314/7a832604714af7043dd619b499185a3d to your computer and use it in GitHub Desktop.
Map a range from one to another in javascript for parallax
//map a range from one to another, protecting limits
Number.prototype.map = function(in_min, in_max, out_min, out_max) {
var output = (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
if (out_max > out_min && output < out_min)
output = out_min;
if (out_max > out_min && output > out_max)
output = out_max;
if (out_max < out_min && output < out_max)
output = out_max;
if (out_max < out_min && output > out_min)
output = out_min;
return output;
}
//Usage for parallax:
$(document).scroll(function(){
var scrolled = window.pageYOffset;
var topOffset = scrolled.map(0, 700, 0, -200); //for scroll position 0 to 700, offset the background by 0 to 200px
$('.parallaxelemnt').css('background-position-y', topOffset);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment