Smooth Scroll Animation With CSS & Javascript – Simple Examples

Welcome to a tutorial on how to add simple smooth scroll animation with pure CSS and Javascript. If you are thinking that the old school “suddenly appear” is too abrupt when we click on a bookmark link, a smooth scroll is actually easy to achieve with modern CSS.

The easiest way to do a smooth scroll animation is to set the scroll behavior property in CSS. I.E. body { scroll-behavior: smooth }

That covers the basics, but let us walk through some examples and 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.

 

 

REAL 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.

 

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.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer 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.

 

SMOOTH SCROLL

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

 

1) CSS SMOOTH SCROLL

1-css-scroll.html
<style>
html, body { scroll-behavior: smooth; }
</style>

<a id="top" href="#bottom">Go to bottom</a>
<div style="height: 1500px; width: 1px;"></div>
<a id="bottom" href="#top">Go to top</a>

Yep, adding scroll-behavior: smooth on the body is actually all we need. The good news is that scroll-behavior is supported on most modern “A grade” browsers, but the bad news is that ancient browsers don’t support it.

 

 

2) SCROLLING WITH JAVASCRIPT

THE HTML

2-js-scroll.html
<!-- (A) SCROLL TO X PIXELS FROM THE TOP -->
<div onclick="goToPixel(800)">
  Go down to exactly 800 pixels from the top.
</div>
 
<!-- (B) SCROLL TO ELEMENT WITH SPECIFIED ID -->
<div id="top" onclick="goToID('#bottom');">
  Go to bottom.
</div>
 
<!-- (C) SCROLL X PIXELS WITH REFERENCE TO CURRENT POSITION -->
<div style="height: 1000px; width: 1px;"></div>
<div onclick="goBy(-300)">
  Go up 300 pixels from current position.
</div>
 
<!-- (X) JUST SOME PAGE PADDING -->
<div style="height: 1000px; width: 1px;"></div>
<div id="bottom" onclick="goToID('#top');">
  Go to top.
</div>

THE JAVASCRIPT

2-js-scroll.js
// (A) SCROLL TO X PIXELS FROM THE TOP
function goToPixel(pix) {
  window.scroll({
    top: pix,
    left: 0,
    behavior: 'smooth'
  });
}
 
// (B) SCROLL TO ELEMENT WITH SPECIFIED ID
function goToID(id) {
  document.querySelector(id).scrollIntoView({
    behavior: 'smooth'
  });
}
 
// (C) SCROLL X PIXELS WITH REFERENCE TO CURRENT POSITION
function goBy(pix) {
  window.scrollBy({
    top: pix,
    left: 0,
    behavior: 'smooth'
  });
}

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 (from the top, bottom, left, right) on the page.
  • scrollBy() will scroll with reference to the current position.
  • scrollIntoView() goes to a specified element.
  • Finally, we need to put in the behavior: 'smooth' option or there will not be any animations.

But as you can guess again, these are not supported in older browsers.

 

 

3) JAVASCRIPT SMOOTH SCROLL FALLBACK

THE HTML

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

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++;
    }
  }
}

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.

 

CSS – SUMMARY

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

 

JAVASCRIPT – SUMMARY

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.