Categories
Tutorials

Smooth Scroll to a specific position in JavaScript

Internal links or in page links are the anchor tags that targets a section in the same page. Normal behavior on clicking these links is an abrupt jump to the target. In other words browsers scroll position jumps to target element.

The most common you see is a back to top button. Which appears when user is at very end of the web page. When it’s clicked we are taken smoothly to top of the page.

So basically this go top button is internally linked to the top of the page.

Reasons for smooth scroll

The smooth transition not only feel nice but this also visually aids us which way the browser is scrolling.

A while back I have achieved similar effect using jQuery.

This time we’ll go with vanilla JavaScript. But before jumping in to the solution, there is something more I want to talk about.

The browser can’t show us all the content at once. A browser need to pass scroll an element to show next element that is not in view. That’s we have a method Element.scrollIntoViewHere the browser will scroll to make that Element visible. This method accept some configuration, I have played with behavior for which smooth is by default. Futher options can be discovered here.

See the Pen scrollIntoView Demo by Samiullah Khan (@samiullah1989) on CodePen.6143

In above demo, you can click on the links to scroll to bottom and top of the page. You can also switch the behavior using the radio buttons.

It’s experimental

So it’s experimental which means that it’s spec is expected to change in the future. By the time of writing this article, caniuse says that the scroll options isn’t supported by some browsers.

But the fallback isn’t that bad

because how wrong things can go, rather than smooth behavior we’ll get that sharp jump.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.