Last active
January 23, 2024 12:44
-
-
Save 8mist/ac88c3a99391e4ecde8ae45fc7cbb5ec to your computer and use it in GitHub Desktop.
Natif smooth scroll
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
const lerp = (a, b, n) => (1 - n) * a + n * b; | |
class SmoothScroll { | |
constructor() { | |
this.DOM = { | |
main: document.querySelector('main'), | |
wrapper: document.querySelector('.site-container') | |
}; | |
if (!this.DOM.main) throw new Error('Please provide a main element.'); | |
if (!this.DOM.wrapper) throw new Error('Please provide a div with a `.site-container` class.'); | |
this.scroll = { | |
ease: 0.07, | |
current: 0, | |
target: 0 | |
}; | |
this.binds(); | |
this.handleResize(); | |
this.setStyle(); | |
this.events(); | |
requestAnimationFrame(() => this.render()); | |
} | |
binds() { | |
this.handleResize = this.handleResize.bind(this); | |
this.handleScroll = this.handleScroll.bind(this); | |
} | |
events() { | |
window.addEventListener('resize', this.handleResize); | |
window.addEventListener('scroll', this.handleScroll); | |
} | |
handleResize() { | |
document.body.style.height = `${this.DOM.wrapper.scrollHeight}px`; | |
} | |
handleScroll() { | |
this.scroll.target = window.pageYOffset || document.documentElement.scrollTop; | |
} | |
setStyle() { | |
Object.assign(this.DOM.main.style, { | |
position: 'fixed', | |
top: 0, | |
left: 0, | |
width: '100%', | |
height: '100%', | |
overflow: 'hidden' | |
}); | |
} | |
transform(element, y) { | |
element.style.transform = `translate3d(0, ${-Math.round(y)}px, 0)`; | |
} | |
render() { | |
this.scroll.current = lerp(this.scroll.current, this.scroll.target, this.scroll.ease); | |
this.scroll.current = Math.floor(this.scroll.current); | |
this.transform(this.DOM.wrapper, this.scroll.current); | |
requestAnimationFrame(() => this.render()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment