sidebar.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Un-active everything when you click it
  2. Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el) {
  3. el.addEventHandler("click", function() {
  4. Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el) {
  5. el.classList.remove("active");
  6. });
  7. el.classList.add("active");
  8. });
  9. });
  10. var updateFunction = function() {
  11. var id;
  12. var elements = document.getElementsByClassName("header");
  13. Array.prototype.forEach.call(elements, function(el) {
  14. if (window.pageYOffset >= el.offsetTop) {
  15. id = el;
  16. }
  17. });
  18. Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el) {
  19. el.classList.remove("active");
  20. });
  21. Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el) {
  22. if (id && id.href.localeCompare(el.href) == 0) {
  23. el.classList.add("active");
  24. }
  25. });
  26. };
  27. // Populate sidebar on load
  28. window.addEventListener('load', function() {
  29. var pagetoc = document.getElementsByClassName("pagetoc")[0];
  30. var elements = document.getElementsByClassName("header");
  31. Array.prototype.forEach.call(elements, function(el) {
  32. var link = document.createElement("a");
  33. // Indent shows hierarchy
  34. var indent = "";
  35. switch (el.parentElement.tagName) {
  36. case "H2":
  37. indent = "20px";
  38. break;
  39. case "H3":
  40. indent = "40px";
  41. break;
  42. case "H4":
  43. indent = "60px";
  44. break;
  45. default:
  46. break;
  47. }
  48. link.appendChild(document.createTextNode(el.text));
  49. link.style.paddingLeft = indent;
  50. link.href = el.href;
  51. pagetoc.appendChild(link);
  52. });
  53. updateFunction.call();
  54. var pop_pagetoc = document.getElementById("pop-sidebar");
  55. Array.prototype.forEach.call(elements, function(el) {
  56. var link = document.createElement("a");
  57. // Indent shows hierarchy
  58. var indent = "";
  59. switch (el.parentElement.tagName) {
  60. case "H2":
  61. indent = "10px";
  62. break;
  63. case "H3":
  64. indent = "20px";
  65. break;
  66. case "H4":
  67. indent = "30px";
  68. break;
  69. default:
  70. break;
  71. }
  72. link.appendChild(document.createTextNode(el.text));
  73. link.style.paddingLeft = indent;
  74. link.href = "javascript:clickToc('"+el.href+"');";
  75. pop_pagetoc.appendChild(link);
  76. });
  77. });
  78. function clickToc(href){
  79. location.href=href;
  80. layer.close(popTocIndex);
  81. }
  82. // Handle active elements on scroll
  83. window.addEventListener("scroll", updateFunction);