diff options
Diffstat (limited to '_includes/sidebar/article-menu.html')
-rw-r--r-- | _includes/sidebar/article-menu.html | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/_includes/sidebar/article-menu.html b/_includes/sidebar/article-menu.html new file mode 100644 index 0000000..aa4184d --- /dev/null +++ b/_includes/sidebar/article-menu.html @@ -0,0 +1,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> |