| 1 | export function scrollTo(selector: string, |
| 2 | parentSelector?: string, |
| 3 | horizontal?: boolean, |
| 4 | distance?: number): void { |
| 5 | // argument validation |
| 6 | let parentEl: HTMLElement, targetEl: HTMLElement; |
| 7 | |
| 8 | parentSelector = parentSelector || 'body'; |
| 9 | |
| 10 | targetEl = <HTMLElement>document.querySelector(selector); |
| 11 | if (!targetEl) { |
| 12 | throw `Invalid selector ${selector}`; |
| 13 | } |
| 14 | |
| 15 | parentEl = <HTMLElement>document.querySelector(parentSelector); |
| 16 | if (!parentEl) { |
| 17 | throw `Invalid parent selector ${parentSelector}`; |
| 18 | } |
| 19 | |
| 20 | // detect the current environment |
| 21 | const parentElStyle = window.getComputedStyle(parentEl); |
| 22 | const scrollContainerEl = parentElStyle.overflow === 'auto' ? parentEl : document.body; |
| 23 | let currentScrollTop = scrollContainerEl.scrollTop; |
| 24 | let currentScrollLeft = scrollContainerEl.scrollLeft; |
| 25 | |
| 26 | // determine targetOffsetTop(or Left); |
| 27 | let targetOffsetTop: number; |
| 28 | let targetOffsetLeft: number; |
| 29 | |
| 30 | if (scrollContainerEl === document.body) { |
| 31 | |
| 32 | const bodyRect = document.body.getBoundingClientRect(); |
| 33 | const targetRect = targetEl.getBoundingClientRect(); |
| 34 | targetOffsetTop = targetRect.top - bodyRect.top; |
| 35 | targetOffsetLeft = targetRect.left - bodyRect.left; |
| 36 | |
| 37 | } else { |
| 38 | |
| 39 | targetOffsetTop = targetEl.offsetTop; |
| 40 | targetOffsetLeft = targetEl.offsetLeft; |
| 41 | |
| 42 | } |
| 43 | |
| 44 | if (distance) { |
| 45 | currentScrollTop += distance; |
| 46 | currentScrollLeft += distance; |
| 47 | } |
| 48 | |
| 49 | |
| 50 | const step = horizontal ? |
| 51 | Math.ceil((targetOffsetLeft - currentScrollLeft) / 10) : |
| 52 | Math.ceil((targetOffsetTop - currentScrollTop) / 10); |
| 53 | const scrollProp = horizontal ? 'scrollLeft' : 'scrollTop'; |
| 54 | ( |
| 55 | |
| 56 | function loop(i: number, prop: any): void { |
| 57 | setTimeout(function main() { |
| 58 | scrollContainerEl[prop] += step; |
| 59 | if (i > 1) { |
| 60 | loop(i - 1, prop); |