Smooth scrolling when clicking an anchor link
First up, scrollIntoView
and behavior: 'smooth'
is the quickest way to achieve smooth scrolling in JavaScript.
This script attaches a click event to all anchor links that point to an id on the page. It then prevents the default jumping motion and replaces it with a buttery smooth scroll to the link's target.
Smooth experience with CSS
So you love CSS? Go turbo and activate native smooth scrolling:
If your page rocks a sticky header, use scroll-padding-top
:
Backward compatibility: A JS answer for older browsers
For elder browsers, like the infamous Internet Explorer, you can use jQuery's animate
:
Splendid practice here is to cache your selectors for a first-class performance:
Playing nice with browsers
Before choosing a scroll method, check if it's well-supported:
scroll-behavior: smooth;
plays well with modern browsers.scrollIntoView
is a_scripts_bases runner with{ behavior: 'smooth' }
.window.scroll
orwindow.scrollBy
can be used with{ behavior: 'smooth' }
for a premium tuning.
Pro tips to level up your smooth scrolling
Accurate URL tracking with history.pushState
To update the URL without reloading a page, sprinkle in history.pushState
:
Include this in the scrollTo
event listener or jQuery's animate callback for the magic.
Accounting for fixed headers
Got a fixed header? Adjust the scroll position accordingly:
Reusable scroll functionality: Save the trees
Keep your work DRY (Don't Repeat Yourself) by bundling your scroll function:
With this function, you can call smooth scrolling whenever you need it.
Code accessibility: Minding your Ps and Qs
Smooth scrolling isn't just ice cream for the eyes ๐ฆ; it should also enhance navigation and accessibility:
- Test with keyboard navigation and screen readers.
- Be mindful of scroll-jacking. Smooth scrolling should make the UX better, not worse.
Was this article helpful?