Skip to content

Instantly share code, notes, and snippets.

@8mist
Last active January 23, 2024 12:44
Show Gist options
  • Save 8mist/ac88c3a99391e4ecde8ae45fc7cbb5ec to your computer and use it in GitHub Desktop.
Save 8mist/ac88c3a99391e4ecde8ae45fc7cbb5ec to your computer and use it in GitHub Desktop.
Natif smooth scroll
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