Created
April 10, 2017 23:07
-
-
Save alana314/7a832604714af7043dd619b499185a3d to your computer and use it in GitHub Desktop.
Map a range from one to another in javascript for parallax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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