Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

scrollToElement

Smoothly scrolls to a specific DOM element.

TypeScript
Copied!
1/**
2 * Smoothly scrolls to a specific DOM element.
3 *
4 * @param element - The target element to scroll to.
5 * @param offset - Optional offset in pixels to adjust scroll position.
6 * @param behavior - Scroll behavior: 'smooth' (default) or 'auto'.
7 */
8export function scrollToElement(
9  element: HTMLElement,
10  offset: number = 0,
11  behavior: ScrollBehavior = 'smooth'
12): void {
13  const rect = element.getBoundingClientRect();
14  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
15
16  window.scrollTo({
17    top: rect.top + scrollTop + offset,
18    behavior,
19  });
20}
  • Smooth Scrolling Experience

    Supports native scrollTo with 'smooth' behavior, enhancing user experience with fluid transitions.

  • Offset Adjustment

    Offers fine control over the final scroll position, making it easy to account for sticky headers or fixed toolbars.

  • Graceful Fallback Support

    Uses window.pageYOffset as a fallback to maintain compatibility across older and modern browsers.

  • Customizable Behavior

    Allows the developer to switch between 'smooth' and 'auto' scroll behaviors for performance or UX needs.

Tests | Examples

TypeScript
Copied!
1let element: HTMLElement;
2
3beforeEach(() => {
4  element = document.createElement('div');
5  document.body.appendChild(element);
6  element.getBoundingClientRect = jest.fn(() => ({
7    top: 100,
8    left: 0,
9    right: 0,
10    bottom: 0,
11    width: 0,
12    height: 0,
13    x: 0,
14    y: 0,
15    toJSON: () => '',
16  }));
17  Object.defineProperty(window, 'scrollTo', {
18    value: jest.fn(),
19    writable: true,
20  });
21});
22
23afterEach(() => {
24  document.body.innerHTML = '';
25  jest.clearAllMocks();
26});
27
28test('scrolls to the element with default options', () => {
29  scrollToElement(element);
30  expect(window.scrollTo).toHaveBeenCalledWith({
31    top: 100 + window.pageYOffset,
32    behavior: 'smooth',
33  });
34});
35
36test('applies offset and custom behavior', () => {
37  scrollToElement(element, -50, 'auto');
38  expect(window.scrollTo).toHaveBeenCalledWith({
39    top: 50 + window.pageYOffset,
40    behavior: 'auto',
41  });
42});

Common Use Cases

  • Navigating to Sections

    Scroll to anchor points or headings in single-page applications or documentation sites.

  • Focus Management

    Automatically scroll to error fields in a form after validation fails.

  • Sticky Navigation Compensation

    Offset scroll position to reveal content below a fixed header.

  • Onboarding or Stepper Interfaces

    Guide users through multi-step interfaces by scrolling to the next section.

  • In-App Scroll Links

    Smoothly transition to content linked via custom navigation menus.

Codebase: Utilities -> Browser & DOM -> scrollToElement | Yevhen Klymentiev