summaryrefslogtreecommitdiff
path: root/_includes/extensions/hashlocate.html
blob: d44b24985e55abdee23c096354cfa48cf21f0efe (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
<script>
  function hashLocate(hashValue) {
    hashValue = hashValue.replace(/^.*#h-/, '');
    var element = document.getElementById(hashValue);

    if (!element) {
      return;
    }

    var headerHeight = 0;
    var header = document.querySelector('header');
    if (header) {
      headerHeight = header.offsetHeight;
    }
    var supportPageOffset = window.pageXOffset !== undefined;
    var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");

    var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft;
    var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;

    var offsetY = element.offsetTop - headerHeight - 12;
    if (y === offsetY) {
      return;
    }

    window.scrollTo(x, offsetY);
  }

  // The first event occurred
  if (window.location.hash) {
    hashLocate(window.location.hash);
  }

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