activebookmark.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Kludge in HTML5 tag recognition in IE8
  2. document.createElement("section");
  3. document.createElement("article");
  4. (function() {
  5. if (!window.addEventListener) return;
  6. var pending = false, prevVal = null;
  7. function updateSoon() {
  8. if (!pending) {
  9. pending = true;
  10. setTimeout(update, 250);
  11. }
  12. }
  13. function update() {
  14. pending = false;
  15. var marks = document.getElementById("nav").getElementsByTagName("a"), found;
  16. for (var i = 0; i < marks.length; ++i) {
  17. var mark = marks[i], m;
  18. if (mark.getAttribute("data-default")) {
  19. if (found == null) found = i;
  20. } else if (m = mark.href.match(/#(.*)/)) {
  21. var ref = document.getElementById(m[1]);
  22. if (ref && ref.getBoundingClientRect().top < 50)
  23. found = i;
  24. }
  25. }
  26. if (found != null && found != prevVal) {
  27. prevVal = found;
  28. var lis = document.getElementById("nav").getElementsByTagName("li");
  29. for (var i = 0; i < lis.length; ++i) lis[i].className = "";
  30. for (var i = 0; i < marks.length; ++i) {
  31. if (found == i) {
  32. marks[i].className = "active";
  33. for (var n = marks[i]; n; n = n.parentNode)
  34. if (n.nodeName == "LI") n.className = "active";
  35. } else {
  36. marks[i].className = "";
  37. }
  38. }
  39. }
  40. }
  41. window.addEventListener("scroll", updateSoon);
  42. window.addEventListener("load", updateSoon);
  43. window.addEventListener("hashchange", function() {
  44. setTimeout(function() {
  45. var hash = document.location.hash, found = null, m;
  46. var marks = document.getElementById("nav").getElementsByTagName("a");
  47. for (var i = 0; i < marks.length; i++)
  48. if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; }
  49. if (found != null) for (var i = 0; i < marks.length; i++)
  50. marks[i].className = i == found ? "active" : "";
  51. }, 300);
  52. });
  53. })();