Created
March 21, 2020 23:01
-
-
Save mikehwagz/8aa0939224ce4c91138aff99b7b1794b to your computer and use it in GitHub Desktop.
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
import { clamp } from '@/util/math' | |
import { on } from '@/util/dom' | |
export function rafScroll(cb) { | |
let tick = false | |
let lastScrollY = 0 | |
const off = on(window, 'scroll', raf) | |
function raf(e) { | |
if (tick) return | |
requestAnimationFrame(run(e)) | |
tick = true | |
} | |
function run(e) { | |
return () => { | |
let scrollY = pageYOffset | |
let delta = -(scrollY - lastScrollY) | |
lastScrollY = scrollY | |
cb(scrollY, delta, e) | |
tick = false | |
} | |
} | |
return off | |
} | |
export function scrollPercentage(el) { | |
const bounds = el.getBoundingClientRect() | |
const vh = window.innerHeight | |
const threshold = 0 | |
const offsetTop = threshold * vh * 0.25 | |
const offsetBottom = threshold * vh * 0.25 | |
return ( | |
1 - | |
clamp( | |
(bounds.bottom - offsetTop) / | |
(vh + bounds.height - offsetBottom - offsetTop), | |
0, | |
1, | |
) | |
) | |
} | |
export function inview(el) { | |
const percent = scrollPercentage(el) | |
return percent > 0 && percent < 1 | |
} | |
export function scrollReset() { | |
if ('scrollRestoration' in history) { | |
history.scrollRestoration = 'manual' | |
} else { | |
window.onbeforeunload = function() { | |
window.scrollTo(0, 0) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment