toc.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*jslint
  2. white: true,
  3. browser: true,
  4. vars: true
  5. */
  6. /**
  7. * Generates a table of contents for your document based on the headings
  8. * present. Anchors are injected into the document and the
  9. * entries in the table of contents are linked to them. The table of
  10. * contents will be generated inside of the first element with the id `toc`.
  11. * @param {HTMLDOMDocument} documentRef Optional A reference to the document
  12. * object. Defaults to `document`.
  13. * @author Matthew Christopher Kastor-Inare III
  14. * @version 20130726
  15. * @example
  16. * // call this after the page has loaded
  17. * htmlTableOfContents();
  18. */
  19. /**
  20. * Modified by @danpros
  21. * select only in #content
  22. * using the heading title as the slug IDs
  23. * insert the anchor inside the heading
  24. * fix browser not scrolling to the hash
  25. */
  26. function htmlTableOfContents (id) {
  27. var documentRef = document;
  28. var toc = documentRef.getElementById('toc');
  29. var headings = [].slice.call(documentRef.body.querySelectorAll('#content h2, #content h3, #content h4, #content h5, #content h6'));
  30. headings.forEach(function (heading, index) {
  31. heading.setAttribute('id', heading.textContent.replace(/\s+/g, '-').toLowerCase() + id);
  32. var link = documentRef.createElement('a');
  33. link.setAttribute('href', '#' + heading.textContent.replace(/\s+/g, '-').toLowerCase() + id);
  34. link.textContent = heading.textContent;
  35. var div = documentRef.createElement('div');
  36. div.setAttribute('class', heading.tagName.toLowerCase() + '-toc');
  37. div.appendChild(link);
  38. toc.appendChild(div);
  39. });
  40. if (window.location.hash) {
  41. var hash = window.location.hash;
  42. scrollToHash(hash);
  43. }
  44. }
  45. // fix browser not scrolling to the hash
  46. function scrollToHash (hash) {
  47. setTimeout(function() {
  48. hashtag = hash;
  49. location.hash = '';
  50. location.hash = hashtag;
  51. }, 300);
  52. }
  53. try {
  54. module.exports = htmlTableOfContents;
  55. } catch (e) {
  56. // module.exports is not defined
  57. }