summaryrefslogtreecommitdiff
path: root/_includes/sidebar/article-menu.html
blob: aa4184d3216860bd75fd95ac9c5ada5491a7b74c (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<style type="text/css" media="screen">
.post-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
</style>

<div class="post-menu">
  <div class="post-menu-title">Contents</div>
  <div class="post-menu-content"></div>
</div>

<script>
  var menu = document.querySelector(".post-menu .post-menu-content");
  var headings = document.querySelector(".post-content").querySelectorAll("h2, h3, h4, h5, h6");

  // Generate post menu
  var menuHTML = '';
  headings.forEach(function (h) {
    menuHTML += (
      '<li class="h-' + h.tagName.toLowerCase() + '">'
      + '<a href="#h-' + h.getAttribute('id') + '">' + h.textContent + '</a></li>');
  });

  menu.innerHTML = '<ul>' + menuHTML + '</ul>';

  // The anchor offsetHeight
  var headerHeight = 0;
  var header = document.querySelector('header');
  if (header) {
    offsetHeight = header.offsetHeight + 12;
  }

  // Active the menu item
  window.addEventListener('scroll', function (event) {
    var lastActive = menu.querySelector('.active');
    var changed = true;
    for (var i = headings.length - 1; i >= 0; i--) {
      var h = headings[i];
      var clientRect = h.getBoundingClientRect();
      if (clientRect.top < offsetHeight) {
        var id = 'h-' + h.getAttribute('id');
        var curActive = menu.querySelector('a[href="#' + id  + '"]');
        if (curActive) {
          curActive.classList.add('active');
        }
        if (lastActive == curActive) {
          changed = false;
        }
        break;
      }
    }
    if (lastActive && changed) {
      lastActive.classList.remove('active');
    }
    event.preventDefault();
  });
</script>