-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscroll.js
More file actions
40 lines (36 loc) · 1.38 KB
/
scroll.js
File metadata and controls
40 lines (36 loc) · 1.38 KB
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
// Vanilla JavaScript Scroll to Anchor
// @ https://perishablepress.com/vanilla-javascript-scroll-anchor/
(function() {
scrollTo();
})();
// function scrollTo() {
// const links = document.querySelectorAll('.scroll');
// links.forEach(each => (each.onclick = scrollAnchors));
// }
function scrollTo() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var link = links[i];
if ((link.href && link.href.indexOf('#') != -1) && ((link.pathname == location.pathname) || ('/' + link.pathname == location.pathname)) && (link.search == location.search)) {
link.onclick = scrollAnchors;
}
}
}
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);
}