-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
export declare function scrollToTop( | ||
el: HTMLElement, | ||
offset: string | number | HTMLElement, | ||
behavior?: ScrollBehavior | ||
): void; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
/** | ||
* Scroll to the top of the element | ||
* @param {HTMLElement} el - The element to scroll to | ||
* @param {string|number|HTMLElement} offset - The offset to apply, can be a number, a string selector or an HTMLElement, default is 0 | ||
* @param {ScrollBehavior} behavior - The scroll behavior, can be 'auto', 'smooth', 'instant', default is 'smooth' | ||
*/ | ||
export function scrollToTop(el, offset = 0, behavior = 'smooth') { | ||
if (!el) { | ||
return; | ||
} | ||
|
||
let offsetEl; | ||
|
||
if (offset instanceof HTMLElement) { | ||
offsetEl = offset; | ||
} | ||
|
||
if (typeof offset === 'string') { | ||
offsetEl = document.querySelector(offset); | ||
} | ||
|
||
if (offsetEl instanceof HTMLElement) { | ||
offset = offset.offsetHeight; | ||
} | ||
|
||
offset = offset || 0; | ||
|
||
const top = Math.max(el.offsetTop, el.getBoundingClientRect().top + window.scrollY) - offset; | ||
if (el && top) { | ||
if ('scrollBehavior' in document.documentElement.style) { | ||
window.scrollTo({ top, behavior }); | ||
} else { | ||
window.scrollTo(0, top); | ||
} | ||
} | ||
} |