3 Ways To Smooth Scroll In CSS Javascript (Simple Examples)

Welcome to a tutorial on how to add smooth scroll animation in CSS and Javascript. Is the “suddenly scroll to” too abrupt for you? Well, it is actually very easy to add smooth scroll animations with modern CSS these days.

The easiest way to add a smooth scroll animation is to set the scroll behavior property in CSS – body { scroll-behavior: smooth }

That covers the basics, but let us walk through some examples and Javascript fallback in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Smooth Scroll Useful Bits & Links
The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SMOOTH SCROLL

All right, let us now get into the various ways and examples of how to do a smooth scroll.

 

1) PURE CSS SMOOTH SCROLL

1-css-scroll.html
<!-- (A) CSS SMOOTH SCROLL -->
<style>
html { scroll-behavior: smooth; }
</style>

<!-- (B) SCROLL TO TOP -->
<p id="top">Top of page</p>
<div style="height: 1500px; width: 100%;"></div>
<a href="#top">Scroll to top</a>

Top of page

Scroll to top

Yep, adding scroll-behavior: smooth on the body is actually all we need. The good news is that scroll-behavior is already well-supported on most modern “A grade” browsers. But if you have to support ancient browsers, the below Javascript method 3 is the only way to go.

 

 

2) JAVASCRIPT SMOOTH SCROLL

THE HTML

2-js-scroll.html
<!-- (A) SCROLL TO X,Y PIXELS FROM THE TOP -->
<button id="top" onclick="scrTo(0, 500)">
  Scroll to 500 px from the top.
</button>
 
<!-- (B) SCROLL X,Y PIXELS FROM CURRENT POSITION -->
<div style="height: 1000px; width: 100%;"></div>
<button onclick="scrBy(0, 100)">
  Scroll down 100 px from current.
</button>
 
<!-- (C) SCROLL TO HTML ELEMENT -->
<div style="height: 1000px; width: 100%;"></div>
<button onclick="scrInto('#top');">
  Go to top.
</button>

 

THE JAVASCRIPT

2-js-scroll.js
// (A) SCROLL TO EXACT POSITION
function scrTo(x, y) {
  window.scroll({
    left: x, top: y,
    behavior: "smooth"
  });
}
 
// (B) SCROLL FROM CURRENT POSITION
function scrBy(x, y) {
  window.scrollBy({
    left: x, top: y,
    behavior: "smooth"
  });
}
 
// (C) SCROLL TO HTML ELEMENT
function scrInto(id) {
  document.querySelector(id).scrollIntoView({
    behavior: "smooth"
  });
}

For you guys who need to do some scrolling programmatically in Javascript, there are 3 essential functions – scroll()scrollBy(), and scrollIntoView().

  • scroll() will go to an exact specified position on the page (from the top, bottom, left, right).
  • scrollBy() will scroll with reference from the current position.
  • scrollIntoView() goes to a specified element.
  • Finally, we set the behavior: "smooth" option to indicate “use smooth scroll animation”.

P.S. As you can guess again, behavior: "smooth" will not work in the older browsers. It will simply “immediately scroll to the specified spot”.

 

 

THE DEMO

 

3) LEGACY JAVASCRIPT SMOOTH SCROLL

THE HTML

3-fallback.html
<button id="top" onclick="sscroll('bottom');">
  Go to bottom
</button>
<div style="height: 2000px; width: 100%;"></div>
<button id="bottom" onclick="sscroll('top');">
  Go to top
</button>

 

THE JAVASCRIPT

3-fallback.js
function sscroll(id) {
  // (A) SCROLL PARAMETERS
  var speed = 10, // Less = faster
      step = 30, // Less = smoother but slower
      click = 0;
 
  // (B) GET CURRENT Y POSITION + TARGET Y POSITION
  var fromY = self.pageYOffset ? self.pageYOffset : document.body.scrollTop ;
  var target = document.getElementById(id);
  var toY = target.offsetTop;
  while (target.offsetParent && target.offsetParent != document.body) {
    target = target.offsetParent;
    toY += target.offsetTop;
  }
 
  // (C) SCROLL ANIMATION - DOWNWARDS
  if (fromY < toY) {
    for (var i=fromY; i<=toY; i+=step) {
      if (i+step > toY) {
        setTimeout("window.scrollTo(0, " + toY + ")", click * speed);
      } else {
        setTimeout("window.scrollTo(0, " + i + ")", click * speed);
      }
      click++;
    }
  }

  // (D) SCROLL ANIMATION - UPWARDS
  else {
    for (var i=fromY; i>=toY; i-=step) {
      if (i-step < toY) {
        setTimeout("window.scrollTo(0, " + toY + ")", click * speed);
      } else {
        setTimeout("window.scrollTo(0, " + i + ")", click * speed);
      }
      click++;
    }
  }
}

Lastly, this is for you guys who have to support the ancient browsers. This is the old-school way of smooth scrolling, and how it works is actually pretty simple:

  • (B) Calculate the current and target Y-positions.
  • (C & D) Then manually set a whole chain of scrollTo() on timers setTimeout() to slowly move towards the target.

 

 

USEFUL BITS & LINKS

That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

 

CSS SMOOTH SCROLL

Property Description Reference Link
 scroll-behavior: smooth Do a smooth scroll, not an “instant scroll”. MDN

 

JAVASCRIPT SMOOTH SCROLL

Function Description Reference Link
 ELEMENT.scrollIntoView() Scroll this element into view. MDN
 window.scroll() Scrolls to a given point on the page. MDN
window.scrollBy() Scrolls with reference to current position. MDN

For fallback, we use a series of scroll with setTimeout, so that it will create an illusion of slowly moving towards the target.

 

INFOGRAPHIC CHEAT SHEET

Smooth Scroll WIth CSS & JS (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.