A Simple Way to Animate Scrolling Effects in JavaScript

William Le

Gone are the days of using JavaScript plugins to animate scrolling. In this article, you’ll learn about a native way to accomplish this that you may not have heard of yet.

It’s actually really easy to natively animate scrolling. Instead of using this syntax that you might familiar with:

window.scroll(0, 1000);  // *jumps* the webpage down 1000px

Use this alternate syntax:

window.scroll({
  top: 1000,
  behavior: 'smooth'  // 👈 
});

That’s it! That will animate the scrolling. It’s a little odd that there’s two wildly different syntaxes for the same method… But it works!

Why Animate Scrolling?

Animating scrolling is a nice touch for users. Without it, the webpage jumps abruptly to something else on the webpage:

It’s easy to feel slightly disoriented, and wonder what just happened. Animating the scrolling effects provides a more pleasant experience:

Using Other Scrolling Methods

There’s actually other scrolling methods besides window.scroll(). These other scroll methods can do things like incrementally scroll a specific distance, or even scroll to a DOM node.

Here’s the various scroll methods that accept the “smooth” scrolling config object:

// incrementally scroll up 100px
window.scrollBy({ top: -100, behavior: 'smooth' });

// scroll to the top
window.scroll({ top: 0, behavior: 'smooth' });

// scroll to a DOM node
document
  .getElementById('kristen-wiig')
  .scrollIntoView({ behavior: 'smooth' });

Try clicking the buttons to play with the scrolling effects!

Conclusion

Try using animated scroll effects in your next project! It’s a nice way to gently guide users to specific parts of your web page that they’ll surely appreciate ✨📜✨

Browser compatibility is solid across the board with the exclusion of Safari, however there's a popular polyfill available that will give you blanket coverage on major browsers.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#