Skip to content

backToTop()

backToTop(top?, behavior?, callback?): (event?) => void

Defined in: src/utils/domUtils.ts:135

Scrolls to the top of the page or a specified vertical position.

This function uses window.scrollTo to scroll to a specified vertical position with a configurable scroll behavior (auto or smooth).

Optionally, a callback can be provided to execute logic after scrolling.

Parameters

top?

number = 0

The vertical scroll position to scroll to (default is 0).

behavior?

The scroll behavior (default is 'smooth').

"auto" | "smooth"

callback?

() => void

Optional callback function to execute after scrolling.

Returns

Function

Parameters

event?

MouseEvent<Element, MouseEvent>

Returns

void

Example

tsx
// Bind it to a button click event
<button onClick={backToTop()}>Back to Top</button>
// Smooth scroll to the top of the page
backToTop();

// Immediate scroll to 100px from the top
backToTop(100, 'auto');

// Scroll to the top and log a message after
backToTop(0, 'smooth', () => console.log('Scrolled to top!'));

Released under the MIT License.