⤎ back to posts

Animating Page Scroll with Anchor Hash

2014-10-17

When using in-page anchor links, you typically create the a tag with the id hash of the element you want to scroll to - <a href=”#your-element”>. The default functionality is to jump the page to that anchor point instantly, without any animation. This can be somewhat confusing for a user, especially if you want your site to be notably vertical and in a specific order.

In order to ensure the page scrolls to that point, you must set a condition when clicking links on your page. Essentially, when you click any <a> tag, you will run a check on the href attribute for any existence of the # hash. If this condition satisfies as true, you can collect the height and offset information of that element from the current position of the page, and animate your scroll to that specific extent.

Example Click me to get past all of these dumb images that Sam has on twitter.

twitter 1 twitter 2 twitter 3

You scrolled down!

This is a great UI technique, and so simple to execute on your page. Here’s the code snippet:

$('a').on('click', function(){
  if($(this).attr('href').indexOf('#')>-1) {
    event.preventDefault();
    var id = $(this).attr("href");
    var top = $(id).offset().top;
    $("html, body").animate({
      scrollTop: top
    }, 500); // you can set any time here
  }
});

Remember, you can manipulate that snippet to effectively do whatever you like when you click a page hash. I tend to offset the page scroll by 20px or so to make sure the element I scroll to has a bit of padding above.

// ...
$("html, body").animate({
  scrollTop: top-20 // 20 pixel offset
}, 500);
// ...
⤎ back to posts