Smooth Scroll

Smooth Scroll

A client-side hook that enables smooth scrolling behavior for anchor links with an automatic offset adjustment.

src/hooks/smooth-scroll.tsx

Usage

import SmoothScroll from '@/hooks/smooth-scroll'
export default function Layout() {
return (
<>
<SmoothScroll />
{/* Your content */}
</>
)
}

Features

  • Automatically attaches smooth scroll behavior to all anchor links (a[href^="#"])
  • Applies a 40px offset from the top when scrolling to anchors
  • Updates the URL hash in browser history
  • Dynamically observes DOM changes to attach listeners to new links
  • Opt-out available by adding no-anchor-scroll class to specific links
  • Reattaches listeners on route changes via Next.js pathname monitoring

How it Works

  • Detects clicks on anchor links starting with #
  • Prevents default browser jump behavior
  • Smoothly scrolls to the target element with offset
  • Updates the URL without page reload
  • Uses MutationObserver to handle dynamically added links

To exclude specific links from smooth scrolling, add the no-anchor-scroll class:

<a
href="#section"
className="no-anchor-scroll"
>
Jump without smooth scroll
</a>

Implementation

The component is used in src/app/layout.tsx to enable smooth scrolling throughout the application.

Support

Talk to the developers of this project to learn more

We have been building professional websites for big clients for over 15 years. Gallop templates and blocks is our best foundation for SEO websites and web apps.

© 2025 Web Plant Media, LLC