Skip to content

Instantly share code, notes, and snippets.

@jesperlandberg
Last active February 19, 2018 13:40
Show Gist options
  • Save jesperlandberg/90ce9b6e6bb4bae367780e3219115bfb to your computer and use it in GitHub Desktop.
Save jesperlandberg/90ce9b6e6bb4bae367780e3219115bfb to your computer and use it in GitHub Desktop.
import TweenMax from 'gsap'
import event from 'dom-events'
import lerp from '~/assets/js/functions/lerp'
export default class Smooth {
constructor() {
this.createBound()
this.content = document.querySelector('.js-scroll-content')
this.sections = [...this.content.querySelectorAll('.js-scroll-section')]
this.cache = []
this.rAF = undefined
}
createBound() {
['setHeight', 'scroll', 'run']
.forEach((fn) => this[fn] = this[fn].bind(this))
}
setHeight() {
document.body.style.height = `${this.content.clientHeight}px`
}
setCache() {
this.sections.forEach((elem, i) => {
const section = {}
section.el = elem
section.sy = 0
section.dy = section.sy
section.ease = `0.1${i * 2}`
this.cache.push(section)
})
}
scroll() {
this.cache.forEach((section) => {
section.sy = window.scrollY
})
}
run() {
this.cache.forEach((section) => {
section.dy = lerp(section.dy, section.sy, section.ease)
section.dy = Math.floor(section.dy * 100) / 100
TweenMax.set(section.el, { y: -section.dy })
})
this.rAF = requestAnimationFrame(this.run)
}
on(requestAnimationFrame = true) {
requestAnimationFrame && this.requestAnimationFrame()
}
off(cancelAnimationFrame = true) {
cancelAnimationFrame && this.cancelAnimationFrame()
}
requestAnimationFrame() {
this.rAF = requestAnimationFrame(this.run)
}
cancelAnimationFrame() {
cancelAnimationFrame(this.rAF)
}
destroy() {
document.body.style.height = ''
this.cache = []
this.off()
}
addEvents() {
this.on()
event.on(window, 'resize', this.setHeight)
event.on(window, 'scroll', this.scroll)
}
removeEvents() {
this.off()
event.off(window, 'resize', this.setHeight)
event.off(window, 'scroll', this.scroll)
}
init() {
this.setHeight()
this.setCache()
this.addEvents()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment