Smooth Scroll to Element
smoothScrollToβ
Smoothly scrolls the webpage to a given HTML element, with optional vertical pixel offset for fine positioning.
Importβ
import { smoothScrollTo } from 'nhb-toolbox';
Function Signatureβ
function smoothScrollTo(element: HTMLElement, offset?: number): void
Usage Examplesβ
- Basic
- With Offset
- Positive Offset
const mySection = document.getElementById('contact');
smoothScrollTo(mySection);
// Smoothly scrolls the page so #contact is at the top.
const mySection = document.getElementById('faq');
smoothScrollTo(mySection, -50);
// Scrolls to #faq, then adjusts up by 50px.
const productList = document.getElementById('products');
smoothScrollTo(productList, 100);
// Scrolls to #products, then moves down 100px.
API Referenceβ
Parametersβ
Name | Type | Description |
---|---|---|
element | HTMLElement | The DOM element to scroll to. |
offset | number | (Optional) Additional vertical offset in pixels (positive = down, negative = up). |
Returnsβ
This function does not return anything (void
).
Key Featuresβ
- Native Smooth Scrolling: Uses
scrollIntoView
with smooth behavior. - Flexible Offset: Supports extra offset for headers/fixed navigation or pixel-perfect alignment.
- No Page Reload: Scrolls in place, with no layout shifts or reloads.
- Easy Integration: Just pass a DOM element and an optional offset.
Limitationsβ
- Browser-only: Requires
window
and DOM APIsβwill not work server-side. - Offset Timing: Offset is applied after a short delay (300ms) to ensure smooth stacking, but timing may require adjustment depending on content/layout speed.
- Vertical Only: Only handles vertical (Y-axis) scrolling.
- No Callback/Event: Does not notify when scrolling is complete.
- Possible Overlap: If new content loads dynamically after scrolling, you may need to call the function again.
Notesβ
- Useful for navigation menus, anchor links, "scroll to top" or "back to section" UX.
- The offset is particularly handy when you have sticky headers or toolbars covering part of the scrolled-to element.
- For complex scenarios, consider listening for scroll events or using Intersection Observer for enhanced visibility tracking.
Recommended Use Casesβ
- Navigating to sections in single-page applications (FAQs, docs, dashboards).
- Scroll-to-anchor feature with header-aware adjustment.
- Enhancing accessibility with keyboard navigation.
- Instant, animated focus for UI feedback (e.g., on form error validation).
Conclusion:
smoothScrollTo
offers developers a simple API for beautiful, modern scrolling experiences, with offset options for perfect UI alignment. Plug it into your navigation or UX flows for a premium feel!