Skip to content

Instantly share code, notes, and snippets.

@FelixLuciano
Last active May 27, 2020 16:28
Show Gist options
  • Save FelixLuciano/78e67c3818f49d991c7b2725c4b4376b to your computer and use it in GitHub Desktop.
Save FelixLuciano/78e67c3818f49d991c7b2725c4b4376b to your computer and use it in GitHub Desktop.
Scroll Transform 💨
const minmax = (value, min = 0, max = 1) => Math.min(Math.max(value, min), max)
function scrollTransform (selector, callback) {
const element = document.querySelector(selector)
const anchor = document.createElement('div')
const scroll = {
get offsetOut () {
value = 1 - (window.scrollY - anchor.offsetTop) / element.offsetHeight
return minmax(value)
},
get offsetIn () {
value = (window.scrollY + window.innerHeight - anchor.offsetTop) / element.offsetHeight
return minmax(value)
},
get offset () {
value = (window.scrollY + window.innerHeight - anchor.offsetTop) / (element.offsetHeight + window.innerHeight)
return minmax(value)
}
}
const callbackCall = event =>
callback.call(element, element, scroll, event)
element.parentNode.insertBefore(anchor, element)
document.addEventListener('scroll', callbackCall, false)
return { element, anchor, scroll }
}
@FelixLuciano
Copy link
Author

Scroll Transform 💨

Usage

const myScroll = scrollTransform('#div', (element, { offsetIn, offsetIn, offset }, event) => {
  element === this
  element.style.opacity = offsetIn
})

// myScroll = { element, anchor, scroll }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment