Skip to content

Instantly share code, notes, and snippets.

@tvthatsme
Last active February 6, 2019 11:57
Show Gist options
  • Save tvthatsme/fe247e143c3d4979159ea1b8c77953f7 to your computer and use it in GitHub Desktop.
Save tvthatsme/fe247e143c3d4979159ea1b8c77953f7 to your computer and use it in GitHub Desktop.
Smooth scrolling
// Define a default animation duration
const defaultAnimationDuration = 6000;
/**
* Smoothly scroll the browser's window up or down a certain number of pixels
*
* @param {Number} pixels - the number of pixels to scroll the screen (positive or negative)
* @param {Number} [time=300] - the amount of time in milliseconds to annimate the scroll
*/
export const smoothScroll = (pixels, time = defaultAnimationDuration) => {
const body = document.documentElement;
const move = -1 * pixels;
// Define the easing curve for the annimation
const easingCurve = 'ease-in-out';
// Define the time to run the annimation (milliseconds)
const timeInSeconds = (time / 1000).toString() + 's';
// Keep a record of the original body styles (if any)
const originalBodyHeight = body.style.height !== '' ? body.style.height : null;
const originalBodyOverflow = body.style.overflow !== '' ? body.style.overflow : null;
// Don't let the user scroll while the animation is running
body.style.height = '100%';
body.style.overflow = 'hidden';
// Set easing time and curve
const transform = `transform ${timeInSeconds} ${easingCurve}`;
body.style.transition = transform;
body.style.webkitTransition = transform;
// Translate the body to where we want to go
const translate = `translateY(${move}px)`;
body.style.transform = translate;
body.style.webkitTransform = translate;
// Once the body reaches the desired position, clean up
setTimeout(() => {
// Remove the transform and translate properties from the body
body.style.transition = null;
body.style.webkitTransition = null;
body.style.transform = null;
body.style.webkitTransform = null;
// Turn scrolling functionality back on
body.style.height = originalBodyHeight;
body.style.overflow = originalBodyOverflow;
// Set the real scroll
window.scrollBy(0, pixels);
}, time);
};
/**
* Smoothly scroll the browser's window to the top
*
* @param {Number} [time=300] - the amount of time in milliseconds to annimate the scroll
*/
export const smoothScrollToTop = (time = defaultAnimationDuration) => {
// Calculate the offset and then use the smooth scroll functionality
const pixels = -1 * window.pageYOffset;
smoothScroll(pixels, time);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment