Smooth scrolling with Javascript

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

Smooth scrolling with 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.

Smooth scrolling with Javascript

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.

The above was not working for you? Feel free to read my article on how to create a website or comment below if you have any questions.

Leave a Reply

Notify of