-
Notifications
You must be signed in to change notification settings - Fork 0
/
smoothscroll.js
31 lines (23 loc) · 963 Bytes
/
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
document.addEventListener('click', function(e) {
if (e.target.className == 'scroll') { // only target elements with class .scroll
scrollAnchors(e, e.target);
}
});
function scrollAnchors(e, respond = null) {
const distanceToTop = el => Math.floor(el.getBoundingClientRect().top);
e.preventDefault();
var targetID = (respond) ? respond.getAttribute('href') : this.getAttribute('href');
const targetAnchor = document.querySelector(targetID);
if (!targetAnchor) return;
const originalTop = distanceToTop(targetAnchor);
window.scrollBy({ top: originalTop, left: 0, behavior: 'smooth' });
const checkIfDone = setInterval(function() {
const atBottom = window.innerHeight + window.pageYOffset >= document.body.offsetHeight - 2;
if (distanceToTop(targetAnchor) === 0 || atBottom) {
targetAnchor.tabIndex = '-1';
targetAnchor.focus();
window.history.pushState('', '', targetID);
clearInterval(checkIfDone);
}
}, 100);
}