Skip to content

Instantly share code, notes, and snippets.

@ivanfgm
Last active September 25, 2018 22:27
Show Gist options
  • Save ivanfgm/059573be01ecf115e2c6 to your computer and use it in GitHub Desktop.
Save ivanfgm/059573be01ecf115e2c6 to your computer and use it in GitHub Desktop.
Scroll detection using a request animation frame for smoothness, implementation for simple parallax.
// Returns the supported property name of a style property from an array of possible names, if non is supported, returns null
function supported_property_name(properties) {
for (var i = 0; i < properties.length; i++) {
if (typeof document.body.style[properties[i]] != "undefined") return properties[i];
}
return null;
}
var transforms = ["transform", "msTransform", "webkitTransform", "mozTransform", "oTransform"];
var transform = supported_property_name(transforms);
/* -------- Nice scroll detection -------- */
// Request animation frame with fallbacks
var frame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function (callback) { window.setTimeout(callback, 1000/60) };
// Preps for animation loop
var top;
var bg_window = document.getElementById('bg-window');
var bg_window_image = document.getElementById('bg-window-image');
// Infinte loop in animation frame
function loop () {
// Avoid calculations if not needed
if (top == window.pageYOffset) {
frame(loop);
return false;
} else top = window.pageYOffset;
if (top <= 300 && top >= 0) {
bg_window_image.style[transform] = "translate3d(0, "+ top*0.1 +"px, 0)";
bg_window.style[transform] = "translate3d(0, "+ top*0.25 +"px, 0)";
}
frame(loop);
}
loop(); // Call the loop for the first time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment