anchor.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /*!
  2. * AnchorJS - v1.2.1 - 2015-07-02
  3. * https://github.com/bryanbraun/anchorjs
  4. * Copyright (c) 2015 Bryan Braun; Licensed MIT
  5. */
  6. function AnchorJS(options) {
  7. 'use strict';
  8. this.options = options || {};
  9. this._applyRemainingDefaultOptions = function(opts) {
  10. this.options.icon = this.options.hasOwnProperty('icon') ? opts.icon : '\ue9cb'; // Accepts characters (and also URLs?), like '#', '¶', '❡', or '§'.
  11. this.options.visible = this.options.hasOwnProperty('visible') ? opts.visible : 'hover'; // Also accepts 'always'
  12. this.options.placement = this.options.hasOwnProperty('placement') ? opts.placement : 'right'; // Also accepts 'left'
  13. this.options.class = this.options.hasOwnProperty('class') ? opts.class : ''; // Accepts any class name.
  14. };
  15. this._applyRemainingDefaultOptions(options);
  16. this.add = function(selector) {
  17. var elements,
  18. elsWithIds,
  19. idList,
  20. elementID,
  21. i,
  22. roughText,
  23. tidyText,
  24. index,
  25. count,
  26. newTidyText,
  27. readableID,
  28. anchor;
  29. this._applyRemainingDefaultOptions(this.options);
  30. // Provide a sensible default selector, if none is given.
  31. if (!selector) {
  32. selector = 'h1, h2, h3, h4, h5, h6';
  33. } else if (typeof selector !== 'string') {
  34. throw new Error('The selector provided to AnchorJS was invalid.');
  35. }
  36. elements = document.querySelectorAll(selector);
  37. if (elements.length === 0) {
  38. return false;
  39. }
  40. this._addBaselineStyles();
  41. // We produce a list of existing IDs so we don't generate a duplicate.
  42. elsWithIds = document.querySelectorAll('[id]');
  43. idList = [].map.call(elsWithIds, function assign(el) {
  44. return el.id;
  45. });
  46. for (i = 0; i < elements.length; i++) {
  47. if (elements[i].hasAttribute('id')) {
  48. elementID = elements[i].getAttribute('id');
  49. } else {
  50. roughText = elements[i].textContent;
  51. // Refine it so it makes a good ID. Strip out non-safe characters, replace
  52. // spaces with hyphens, truncate to 32 characters, and make toLowerCase.
  53. //
  54. // Example string: // '⚡⚡⚡ Unicode icons are cool--but they definitely don't belong in a URL fragment.'
  55. tidyText = roughText.replace(/[^\w\s-]/gi, '') // ' Unicode icons are cool--but they definitely dont belong in a URL fragment'
  56. .replace(/\s+/g, '-') // '-Unicode-icons-are-cool--but-they-definitely-dont-belong-in-a-URL-fragment'
  57. .replace(/-{2,}/g, '-') // '-Unicode-icons-are-cool-but-they-definitely-dont-belong-in-a-URL-fragment'
  58. .substring(0, 64) // '-Unicode-icons-are-cool-but-they-definitely-dont-belong-in-a-URL'
  59. .replace(/^-+|-+$/gm, '') // 'Unicode-icons-are-cool-but-they-definitely-dont-belong-in-a-URL'
  60. .toLowerCase(); // 'unicode-icons-are-cool-but-they-definitely-dont-belong-in-a-url'
  61. // Compare our generated ID to existing IDs (and increment it if needed)
  62. // before we add it to the page.
  63. newTidyText = tidyText;
  64. count = 0;
  65. do {
  66. if (index !== undefined) {
  67. newTidyText = tidyText + '-' + count;
  68. }
  69. // .indexOf is supported in IE9+.
  70. index = idList.indexOf(newTidyText);
  71. count += 1;
  72. } while (index !== -1);
  73. index = undefined;
  74. idList.push(newTidyText);
  75. // Assign it to our element.
  76. // Currently the setAttribute element is only supported in IE9 and above.
  77. elements[i].setAttribute('id', newTidyText);
  78. elementID = newTidyText;
  79. }
  80. readableID = elementID.replace(/-/g, ' ');
  81. // The following code builds the following DOM structure in a more effiecient (albeit opaque) way.
  82. // '<a class="anchorjs-link ' + this.options.class + '" href="#' + elementID + '" aria-label="Anchor link for: ' + readableID + '" data-anchorjs-icon="' + this.options.icon + '"></a>';
  83. anchor = document.createElement('a');
  84. anchor.className = 'anchorjs-link ' + this.options.class;
  85. anchor.href = '#' + elementID;
  86. anchor.setAttribute('aria-label', 'Anchor link for: ' + readableID);
  87. anchor.setAttribute('data-anchorjs-icon', this.options.icon);
  88. if (this.options.visible === 'always') {
  89. anchor.style.opacity = '1';
  90. }
  91. if (this.options.icon === '\ue9cb') {
  92. anchor.style.fontFamily = 'anchorjs-icons';
  93. anchor.style.fontStyle = 'normal';
  94. anchor.style.fontVariant = 'normal';
  95. anchor.style.fontWeight = 'normal';
  96. anchor.style.lineHeight = 1;
  97. }
  98. if (this.options.placement === 'left') {
  99. anchor.style.position = 'absolute';
  100. anchor.style.marginLeft = '-1em';
  101. anchor.style.paddingRight = '0.5em';
  102. elements[i].insertBefore(anchor, elements[i].firstChild);
  103. } else { // if the option provided is `right` (or anything else).
  104. anchor.style.paddingLeft = '0.375em';
  105. elements[i].appendChild(anchor);
  106. }
  107. }
  108. return this;
  109. };
  110. this.remove = function(selector) {
  111. var domAnchor,
  112. elements = document.querySelectorAll(selector);
  113. for (var i = 0; i < elements.length; i++) {
  114. domAnchor = elements[i].querySelector('.anchorjs-link');
  115. if (domAnchor) {
  116. elements[i].removeChild(domAnchor);
  117. }
  118. }
  119. return this;
  120. };
  121. this._addBaselineStyles = function() {
  122. // We don't want to add global baseline styles if they've been added before.
  123. if (document.head.querySelector('style.anchorjs') !== null) {
  124. return;
  125. }
  126. var style = document.createElement('style'),
  127. linkRule =
  128. ' .anchorjs-link {' +
  129. ' opacity: 0;' +
  130. ' text-decoration: none;' +
  131. ' -webkit-font-smoothing: antialiased;' +
  132. ' -moz-osx-font-smoothing: grayscale;' +
  133. ' }',
  134. hoverRule =
  135. ' *:hover > .anchorjs-link,' +
  136. ' .anchorjs-link:focus {' +
  137. ' opacity: 1;' +
  138. ' }',
  139. anchorjsLinkFontFace =
  140. ' @font-face {' +
  141. ' font-family: "anchorjs-icons";' +
  142. ' font-style: normal;' +
  143. ' font-weight: normal;' + // Icon from icomoon; 10px wide & 10px tall; 2 empty below & 4 above
  144. ' src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMg8SBTUAAAC8AAAA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CuAAEAAAAAAAEADgAAAAEAAAAAAAIABwCfAAEAAAAAAAMADgBLAAEAAAAAAAQADgC0AAEAAAAAAAUACwAqAAEAAAAAAAYADgB1AAEAAAAAAAoAGgDeAAMAAQQJAAEAHAAOAAMAAQQJAAIADgCmAAMAAQQJAAMAHABZAAMAAQQJAAQAHADCAAMAAQQJAAUAFgA1AAMAAQQJAAYAHACDAAMAAQQJAAoANAD4YW5jaG9yanMtaWNvbnMAYQBuAGMAaABvAHIAagBzAC0AaQBjAG8AbgBzVmVyc2lvbiAxLjAAVgBlAHIAcwBpAG8AbgAgADEALgAwYW5jaG9yanMtaWNvbnMAYQBuAGMAaABvAHIAagBzAC0AaQBjAG8AbgBzYW5jaG9yanMtaWNvbnMAYQBuAGMAaABvAHIAagBzAC0AaQBjAG8AbgBzUmVndWxhcgBSAGUAZwB1AGwAYQByYW5jaG9yanMtaWNvbnMAYQBuAGMAaABvAHIAagBzAC0AaQBjAG8AbgBzRm9udCBnZW5lcmF0ZWQgYnkgSWNvTW9vbi4ARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==) format("truetype");' +
  145. ' }',
  146. pseudoElContent =
  147. ' [data-anchorjs-icon]::after {' +
  148. ' content: attr(data-anchorjs-icon);' +
  149. ' }',
  150. firstStyleEl;
  151. style.className = 'anchorjs';
  152. style.appendChild(document.createTextNode('')); // Necessary for Webkit.
  153. // We place it in the head with the other style tags, if possible, so as to
  154. // not look out of place. We insert before the others so these styles can be
  155. // overridden if necessary.
  156. firstStyleEl = document.head.querySelector('[rel="stylesheet"], style');
  157. if (firstStyleEl === undefined) {
  158. document.head.appendChild(style);
  159. } else {
  160. document.head.insertBefore(style, firstStyleEl);
  161. }
  162. style.sheet.insertRule(linkRule, style.sheet.cssRules.length);
  163. style.sheet.insertRule(hoverRule, style.sheet.cssRules.length);
  164. style.sheet.insertRule(pseudoElContent, style.sheet.cssRules.length);
  165. style.sheet.insertRule(anchorjsLinkFontFace, style.sheet.cssRules.length);
  166. };
  167. }
  168. var anchors = new AnchorJS();