Also available in: Français

Not so long ago I saw one of the developers I work with writing a very complex function to allow a smooth scrolling to a lower element on the page. I was quite surprised that he doesn’t use scrollIntoView() and his behavior parameter and its smooth value. Did you heard of it?

When you are used to doing things in a certain way, it is difficult to question yourself, especially when projects are a little tense in terms of timing. Often, even as developers, you tend to create a small file of utilities or helpers to avoid having to rewrite the small useful functions that you are used to reusing.

I wrote a little function myself a while ago using jQuery (yes, it’s way outdated: p), but it’s in french ^^”
Smoothscroll in jQuery.

Smooth-scroll on click with scrollIntoView()

Imagine an internal anchor in a page, when the user clicks on the link you want to propose a smooth scrolling to the beginning of this element (here the target is #part-3). This is possible with this little piece of JavaScript.

const target = document.getElementById('part-3'),
button = document.getElementById('goto');

button.addEventListener('click', function(){

target.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'nearest'
});

});

As you can see, there’s nothing very complicated about it. The parameters are as follows, they are all optional:

  • block : which part of the block you want to reach, among start, center, end or nearest (by default start).
  • behavior : how to reach this block, among the options auto or smooth, (by defaut auto).
  • inline : where to reach the element if it’s a horizontal scrolling, among start, center, end or nearest (by default nearest)

A little demonstration on CodePen to help you picture this.

Voir la démo sur CodePen 0

SmoothScroll when adding an element

One of the use cases that occurs quite regularly is the case of an addition of section in a page after a user action, or a new element in a list for example. This is a good way for the user to better understand what just happened on the screen by guiding them to the element they have asked to add.

Here is a little demo of a todo list using localStorage to save your list and scrollIntoView()  to bring you to the new elements.

See the demo

I started a demo on CodePen  but it’s kind of buggy because CodePen don’t know how to load data from localStorage. But you can play with it and fork it if you want to.

Voir la démo sur CodePen 0

A look to the support.

Goind further in CSS

CSS use the same approach to customize the scroll behavior when an element is scrollable. Learn more about it thanks to this article: CSS Smooth-Scrolling avec Scroll-Behavior.

Don’t hesitate to share your use case in the comments 🙂