Smooth scrolling with Vanilla JS

10 min to read

Since I’m refusing to use jQuery all the time to do scroll animations here’s a way to animate smooth scrolling with vanilla JS.

Using jQuery

Using jQuery it’s quite straight forward:

$('html, body').animate({
    scrollTop: $("#target-element").offset().top
}, 1000);

This will animate the page to scroll towards a specific offset, and the duration will be 1s.

Using Vanilla JS

Since jQuery is quite big as a package I rather not use it because everything is possible with vanilla JS.

  top: document.getElementById('target-element').offsetTop, 
  left: 0, 
  behavior: 'smooth' 

If you don’t the behaviour you will not have the scrolling effect, it will jump to the position of the target element.

You can also scroll an amount relative to the current position using scrollBy.

  top: 100,
  left: 0, 
  behavior: 'smooth' 

To scroll upwards, you need to use a negative value.

Comment below if you have any questions!