blog/_includes/extensions/hashlocate.html

41 lines
1,021 B
HTML
Raw Normal View History

2019-09-11 06:19:34 +02:00
<script>
function hashLocate(hashValue) {
hashValue = hashValue.replace(/^.*#h-/, '');
var element = document.getElementById(hashValue);
if (!element) {
return;
}
var header = document.querySelector('header');
var scrollPos = getScrollPos();
var offsetY = element.offsetTop - (header.offsetTop + header.offsetHeight + 20);
2019-09-11 06:19:34 +02:00
if (offsetY == scrollPos.y) {
2019-09-11 06:19:34 +02:00
return;
}
if (header.offsetTop == 0 && offsetY > scrollPos.y) {
offsetY += header.offsetHeight;
} else if (header.offsetTop < 0 && offsetY < scrollPos.y) {
offsetY -= header.offsetHeight;
}
smoothScrollTo(offsetY);
2019-09-11 06:19:34 +02:00
}
// The first event occurred
window.addEventListener('load', function(event) {
if (window.location.hash) {
hashLocate(window.location.hash);
}
});
2019-09-11 06:19:34 +02:00
// The first event occurred
2019-09-11 06:19:34 +02:00
window.addEventListener('click', function(event) {
if (event.target.matches('a')) {
hashLocate(event.target.getAttribute('href'));
}
});
</script>