Skip to content

Commit

Permalink
Provide scroll util
Browse files Browse the repository at this point in the history
  • Loading branch information
Schascha committed Feb 2, 2024
1 parent 8081fc8 commit 1cda592
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,25 @@ console.log(groupBy(array, 'group'));
*/
```

### Scroll

#### `scrollToTop(el, offset, behavior)`

Scroll to the top of the element.

```javascript
import { scrollToTop } from '@schascha/brabbelback';

const el = document.querySelector('.el');
scrollToTop(el);

// Scroll to element with sticky header
scrollToTop(el, '.header');

// Scroll to element with offset
scrollToTop(el, 100);
```

### Type

#### `typeOf(value)`
Expand Down
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ export * from './src/cookie';
export * from './src/copy';
export * from './src/date';
export * from './src/filter';
export * from './src/scroll';
export * from './src/type';
export * from './src/visible';
5 changes: 5 additions & 0 deletions src/scroll.d.ts
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;
36 changes: 36 additions & 0 deletions src/scroll.js
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);
}
}
}

0 comments on commit 1cda592

Please sign in to comment.