Created
November 30, 2017 20:58
-
-
Save kristofferh/d02056919bdf5d045d8e1c21d720cb6b to your computer and use it in GitHub Desktop.
Momentum effect for sticky/fixed elements
This file contains 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
let element; | |
let scrollTop = 0; | |
let pinTop = 0; | |
let lastTime; | |
let options = { | |
lag: 50, | |
maxSpeed: 100, | |
frameRate: 30 | |
}; | |
const updatePosition = time => { | |
const { lag, maxSpeed, frameRate } = options; | |
if (!lastTime) { | |
lastTime = time; | |
} | |
let delta = time - lastTime; | |
if (delta >= frameRate) { | |
scrollTop = window.pageYOffset; | |
var move = Math.round((scrollTop - pinTop) * delta / (lag + delta)); | |
var direction = move === 0 ? 0 : move / Math.abs(move); | |
pinTop = pinTop + Math.min(Math.abs(move), maxSpeed) * direction; | |
Object.assign(element.style, { | |
transform: `translateY(${-move}px`, | |
transition: 'transform 0.2s ease' | |
}); | |
lastTime = time; | |
} | |
requestAnimationFrame(updatePosition); | |
}; | |
const momentumSticky = (el, opts = {}) => { | |
element = el; | |
options = { ...options, ...opts }; | |
requestAnimationFrame(updatePosition); | |
}; | |
export default momentumSticky; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment