October 17, 2014
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.
This is a great UI technique, and so simple to execute on your page. Here’s the code snippet:
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.⤎ back to posts