DEV Community

Piotr Pogorzelski
Piotr Pogorzelski

Posted on

Anchor links with smooth scrolling

CSS solution

Anchor links bring us to sections of a page they link to instantaneously. We can replace this "teleportation" with smooth scrolling animation, using single CSS property:

html {
  scroll-behavior: smooth;
}
Enter fullscreen mode Exit fullscreen mode

Unfortunately this does not work on Safari. Truly, safari is a new IE6.

Javascript solution

Fortunately, we can achieve a smooth scrolling effect with a bit of jQuery code.

The snippet below simulates smooth anchor clicking with all its aspects. Thanks to use of history API, back and forward browser buttons work. If user starts scrolling while the animation is still running, it stops to avoid "fighting" with animation movement.

  $('a[href^="#"]').on('click', function(event) {
    var hash = '#' + $(this).attr('href').split('#')[1]
    var element = $(hash)
    if (element.length) {
      event.preventDefault();
      history.pushState(hash, undefined, hash)
      $('html, body').animate({scrollTop: element.offset().top}, 500)
    }
  });   

  window.addEventListener('popstate', function(e) {
    if(e.state && e.state.startsWith('#') && $(e.state).length){
      $('html, body').animate({scrollTop: $(e.state).offset().top}, 500)
    }
  });

  $('html, body').on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
    $('html, body').stop();
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
johnfound profile image
johnfound

What is wrong with the teleportation? It makes browsing faster and needs less energy from my netbook batteries.

Collapse
 
juuyan profile image
Yan

Yeah web site exists for the visitors...But for many products developers are not average user as well.

Collapse
 
piotrpog profile image

Some clients want such eye candy. Unfortunately webdevs don't rule the world.

Collapse
 
johnfound profile image
johnfound

But generally, the web site exists for the visitors, not for the owners. Isn't it?

Thread Thread
 
piotrpog profile image

If owners pays for a website, then a website exists for them.
Sometimes website needs to look as flashy as possible, and laptop battery be damned.