Smooth Scroll in native Javascript/css

Reading Time 2 min

How to get a smooth scroll without using Jquery ? or any other library? As of 2020, such a trivial task is well supported natively by browsers. Smooth scroll can be achieved via pure javascript or even pure css. Lets check out how to smooth scroll natively using both the ways.


Smooth Scroll in native javascript, css

Smooth scroll in pure Css

Set the scroll-behaviour property to smooth on any class (or the whole body) to have smooth scrolling enabled. By default, scroll-behaviour is set to auto which means that the scrolling happens instantly without any scrolling animation.

Syntax

.classA {
    scroll-behavior: smooth;  // default value is 'auto'
s}

Here’s a codepen to demonstrate this in action.

See the Pen
Scrolling Box w/ `scroll-behavior`
by CSS-Tricks (@css-tricks)
on CodePen.

Browser Support

According to caniuse data, the scroll-behavior property is supported in all major browsers except IE, Edge* and Safari. If you must support these browsers as well, take a look at setting up smooth scroll in pure javascript which has a better browser support. (Note* that Edge version 76 and above is supported.)


Smooth scroll in pure Javascript

You can use the native javascript window.scroll() or window.scrollTo() function to have a smooth scroll. The key is to pass the behavior: 'smooth' option which allows for smooth scrolling. The syntax is shown below –

// Scroll to specific values
window.scroll({
  top: 1500, 
  left: 0, 
  behavior: 'smooth'
});

window.scrollTo({
  top: 100, 
  behavior: 'smooth'
});

The scrollTo method can also be used on any element. This is demonstrated below –

There are some more handy native javascript functions like the window.scrollBy() function which can be used to smooth scroll a certain amount from the current position and the Element.scrollIntoView() function that can be used to smooth scroll to a certain element.

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

Browser Support

According to caniuse, the browser support for these is quite good and as of 2020 all browsers except IE and Edge version 18 & below are supported. For the unsupported versions, there is a polyfill available which can be used instead.


Jquery Fallback for Legacy Browsers

I strongly recommend using the polyfill mentioned above for smooth scrolling. However, if you insist on using jQuery, here is a snippet that should help…


References

Leave a Reply