-
Notifications
You must be signed in to change notification settings - Fork 0
/
smoothScroll.js
53 lines (42 loc) · 1.6 KB
/
smoothScroll.js
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
let scrollSpeed = 40;
let currentScroll = window.scrollY;
let targetScroll = currentScroll;
let inertia = 0.001;
function smoothScroll() {
currentScroll += (targetScroll - currentScroll) * inertia;
window.scrollTo(0, currentScroll);
if (Math.abs(targetScroll - currentScroll) > 0.1) {
requestAnimationFrame(smoothScroll);
}
}
window.addEventListener('wheel', function(event) {
event.preventDefault();
targetScroll += event.deltaY > 0 ? scrollSpeed : -scrollSpeed;
smoothScroll();
}, { passive: false });
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href');
const targetElement = document.querySelector(targetId);
if (targetElement) {
targetScroll = targetElement.offsetTop;
const startScroll = currentScroll;
const distance = targetScroll - startScroll;
const duration = 300;
const startTime = performance.now();
function animateScroll(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const newScroll = startScroll + distance * progress;
window.scrollTo(0, newScroll);
if (progress < 1) {
requestAnimationFrame(animateScroll);
} else {
currentScroll = newScroll;
}
}
requestAnimationFrame(animateScroll);
}
});
});