summaryrefslogtreecommitdiff
path: root/_includes/extensions/hashlocate.html
blob: 6faf553b990eb60efc57702d14b244cee674315f (plain)
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
<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);

    if (offsetY  == scrollPos.y) {
      return;
    }

    if (header.offsetTop == 0  && offsetY > scrollPos.y) {
      offsetY += header.offsetHeight;
    } else if (header.offsetTop < 0  && offsetY < scrollPos.y) {
      offsetY -= header.offsetHeight;
    }

    smoothScrollTo(offsetY);
  }

  // The first event occurred
  window.addEventListener('load', function(event) {
    if (window.location.hash) {
      hashLocate(window.location.hash);
    }
  });

  // The first event occurred
  window.addEventListener('click', function(event) {
    if (event.target.matches('a')) {
      hashLocate(event.target.getAttribute('href'));
    }
  });
</script>