Last active
April 14, 2017 00:08
-
-
Save callmecavs/b9b1bedccd5a4904ef1ca3401224ed7e to your computer and use it in GitHub Desktop.
horizontal container scrolling (modified jump.js)
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
// ease in out quad | |
const easing = (t, b, c, d) => { | |
t /= d / 2 | |
if (t < 1) return c / 2 * t * t + b | |
t-- | |
return -c / 2 * (t * (t - 2) - 1) + b | |
} | |
// modified jump.js | |
// stripped options, supports (only) scrolling a container horizontally | |
const jumper = () => { | |
let cb | |
let start | |
let next | |
let end | |
let distance | |
let duration | |
let scroller | |
let timeCurrent | |
let timeElapsed | |
let timeStart | |
function horiz (target, from, to, options = {}) { | |
// cache options | |
cb = options.callback | |
duration = options.duration || 1000 | |
end = to | |
start = from | |
scroller = target | |
// determine scroll distance | |
distance = to - from | |
// start it up | |
window.requestAnimationFrame(run) | |
} | |
function run (timeCurrent) { | |
// store time scroll started, if not started already | |
if (!timeStart) { | |
timeStart = timeCurrent | |
} | |
// determine time spent scrolling so far | |
timeElapsed = timeCurrent - timeStart | |
// calculate next scroll position | |
next = easing(timeElapsed, start, distance, duration) | |
// scroll to it | |
scroller.scrollLeft = next | |
// check progress | |
timeElapsed < duration | |
? window.requestAnimationFrame(run) | |
: done() | |
} | |
function done () { | |
// account for rAF time rounding inaccuracies | |
scroller.scrollLeft = start + distance | |
// fire callback | |
if (typeof cb === 'function') { | |
cb() | |
} | |
// reset for next jump | |
timeStart = false | |
} | |
return horiz | |
} | |
// export singleton | |
const singleton = jumper() | |
export default singleton |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment