Animate scrolling to an element in Javascript

Spent quite a while looking into different ways to animate scrolling on a page, many of which required jQuery.

I'm not against jQuery, by any means, but importing a whole library for that alone seems a bit overkill. Plus, I've managed to survive without it so far.

Little did I realise, there is actually a method that allows you to scroll directly to an element:

var elem = document.getElementById("myElem")

Great! But this happens automatically. I'd like to be able to smoothly scroll up and down the page automatically when this is called.

Fortunately, there are options that can be passed into the method:

var elem = document.getElementById("myElem")
elem.scrollIntoView({ behavior: 'smooth' })

You can see the result (on desktop) in the side navigation on the right of this page.

Options for scrollIntoView

As well as setting the behavior to smooth, there are the following options:

  • block - Define where the page aligns vertically. Options are start, center, end or nearest. Default is start.
  • inline - Define where the page aligns horizontally. Options are start, center, end or nearest. Default is nearest.


Like many great features, browser support isn't 100%.

Fortunately, all modern browsers support scrollIntoView, however the option to scroll smoothly isn't supported in any version of IE, Safari, Safari on iOS, or Android browser. gives a good illustration of which browsers don't support this option: Can I use: scrollIntoView.

The good news is that supplying the options that aren't supported on these browsers doesn't break anything. The smooth option is just ignored.