Smooth Scrolling for Screencasts
Let’s say you wanted to scroll a web page from top to bottom programmatically. For example, you’re recording a screencast and want a nice full-page scroll. You probably can’t scroll it yourself because it’ll be all uneven and jerky. Native JavaScript can do smooth scrolling. Here’s a tiny snippet that might do the trick for you:
window.scrollTo({
top: document.body.getBoundingClientRect().height,
behavior: 'smooth'
});
But there is no way to control the speed or easing of that! It’s likely to be way too fast for a screencast. I found a little trick though, originally published by (I think) Jedidiah Hurt.
The trick is to use CSS transforms instead of actual scrolling. This way, both speed and easing can be controlled. Here’s the code that I cleaned up a little:
const scrollElement = (element, scrollPosition, duration) => {
// useful while testing to re-run it a bunch.
// element.removeAttribute("style");
const style = element.style;
style.transition = duration + 's';
style.transitionTimingFunction = 'ease-in-out';
style.transform = 'translate3d(0, ' + -scrollPosition + 'px, 0)';
}
scrollElement(
document.body,
(
document.body.getBoundingClientRect().height
-
document.documentElement.clientHeight
+
25
),
5
);
The idea is to transform a negative top position for the height of the entire document, but subtract the height of what you can see so it doesn’t scroll too far. There is a little magic number in there you may need to adjust to get it just right for you.
Here’s a movie I recorded that way:
Another possibility is a little good ol’ fashioned jQuery .animate(), which can be extended with some custom easing. Here’s a demo of that.
See the Pen
jQuery Smooth Scrolling with Easing by Chris Coyier (@chriscoyier)
on CodePen.
The post Smooth Scrolling for Screencasts appeared first on CSS-Tricks.