Skip to content

Commit 68457d2

Browse files
author
Manuel Mujica
authored
Merge pull request #7 from bit-docs/github-ids
Use github approach to generate anchor heading ids
2 parents 0303eb6 + 9cd3e47 commit 68457d2

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

toc.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ function throttle(fn, ms){
2020
};
2121
}
2222

23+
function makeAnchorHeadingId(anchorText) {
24+
return (anchorText || "")
25+
.replace(/\s/g, "-") // replace spaces with dashes
26+
.replace(/[^\w\-]/g, "") // remove punctuation
27+
.toLowerCase();
28+
}
29+
2330
function outerHeight(el) {
2431
var height = el.offsetHeight;
2532
var style = getComputedStyle(el);
@@ -98,9 +105,17 @@ var TableOfContents = Control.extend({
98105
var titles = selector ? document.querySelectorAll(selector) : [];
99106
var curScroll = this.scroller.scrollTop;
100107
var navHeight = this.navHeight;
101-
return [].map.call(titles, function(title, idx){
108+
var headings = {};
109+
110+
return [].map.call(titles, function(title, idx) {
102111
var txt = title.textContent;
103-
title.id = 'section_' + txt.replace(/\s/g,"").replace(/[^\w]/g,"_");
112+
var id = makeAnchorHeadingId(txt);
113+
var count = headings[id] || 0;
114+
115+
// add unique id if we get headings with the same text
116+
title.id = makeAnchorHeadingId(txt) + (count > 0 ? "-" + count : "");
117+
headings[id] = count + 1;
118+
104119
return {
105120
id: title.id,
106121
index: idx,

0 commit comments

Comments
 (0)