CSS Smooth Scrolling

From Logic Wiki
Jump to: navigation, search

Definition

The scrollIntoView API can be instructed to animate the scrolling part by adding the behavior property on the scrollIntoViewOption object.

element.scrollIntoView({ behavior: 'smooth' });

scrollIntoViewOption currently only works on Firefox and Chrome.

JS

console.clear();

// This works on Firefox and Chrome

// Everytime someone clicks on something
document.body.addEventListener('click', e => {
  
  const href = e.target.href;
  
  // no href attribute, no need to continue then
  if (!href) return;
  
  const id = href.split('#').pop();
  const target = document.getElementById(id);
  
  // no target to scroll to, bail out
  if (!target) return;
  
  // prevent the default quick jump to the target
  e.preventDefault();
  
  // set hash to window location so history is kept correctly
  history.pushState({}, document.title, href);
  
  // smooooooth scroll to the target!
  target.scrollIntoView({
    behavior: 'smooth',
    block: 'start'
  });

});

css

There's a scroll-behavior CSS property that we can set to smooth, it's literally that literal.

scroll-behavior: smooth

Scroll distance matters

If there is a lot of distance to travel, Firefox will skip content to keep the scroll time-limited, while Chrome has a max velocity and will just take its time to get to the target.