-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhd-smooth-scroll.ts
66 lines (53 loc) · 1.96 KB
/
hd-smooth-scroll.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*! hd-smooth-scroll v1.0.1 | MIT | https://github.com/hd-code/hd-smooth-scroll */
document.addEventListener("DOMContentLoaded", () => {
const links = document.links;
for (let i = 0, ie = links.length; i < ie; i++) {
handleLink(links[i] as HTMLAnchorElement);
}
function handleLink(link: HTMLAnchorElement) {
// stop func if link doesn't refer to the current page
if (
link.hostname !== location.hostname ||
link.pathname !== location.pathname
) {
return;
}
link.addEventListener("click", (event) => handleClick(event, link));
}
function handleClick(event: MouseEvent, link: HTMLAnchorElement) {
// get target element, stop func if there is no target
const hash = link.hash.slice(1);
const target = hash ? document.getElementById(hash) : document.body;
if (!target) {
return;
}
event.preventDefault(); // prevent immediate jump to target
smoothScroll(target.getBoundingClientRect().top, hash);
}
const numOfSteps = 50;
const stepDuration = 10;
let isScrolling = false;
function smoothScroll(distance: number, hash: string) {
if (isScrolling) {
return;
}
isScrolling = true;
const currentXPos =
window.pageXOffset || document.documentElement.scrollLeft;
const currentYPos =
window.pageYOffset || document.documentElement.scrollTop;
const stepLength = distance / numOfSteps;
let i = 1;
const scrollAStep = () => {
const targetYPos = currentYPos + i * stepLength;
window.scrollTo(currentXPos, targetYPos);
if (++i < numOfSteps) {
setTimeout(scrollAStep, stepDuration);
} else {
isScrolling = false;
location.hash = hash;
}
};
setTimeout(scrollAStep, stepDuration);
}
});