Skip to content

Instantly share code, notes, and snippets.

@redonkulus
Created July 25, 2012 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redonkulus/3176259 to your computer and use it in GitHub Desktop.
Save redonkulus/3176259 to your computer and use it in GitHub Desktop.
TOC example
/**
* Used with Styledocco
* Dynamically create table of contents from H1's on page
*/
(function () {
'use strict';
var x, header, article, link,
container = document.querySelector('section.container'),
sections = container.getElementsByTagName('article'),
length = sections.length,
items = [],
tocEl = document.getElementById('toc');
// parse each section, extract H1 title and push to 'toc' array
if (sections) {
for (x = 0; x < length; x+=1) {
article = sections[x];
if (article) {
header = article.getElementsByTagName('h1')[0].innerText;
link = article.querySelector('a.permalink').href;
items.push('<li><a href="' + link + '">' + header + '</a></li>');
}
}
}
// generate table of contents markup
tocEl.innerHTML = '<ul>' + items.join('') + '</ul>';
}());
@raimonizard
Copy link

Hi there!
How to use this code and add it in my markdown Gist publications?

Do I need to execute it offline and then upload the resulting TOC into the markdown file in Gist? Or can I embbed this inside the markdown file in Gist to make it dynamic every time I do a change on the articles?

Thanks and regards,
Raimon

@redonkulus
Copy link
Author

I dont think GitHub will run arbitrary JS code that you put in a gist as there could be security concerns with that.

@raimonizard
Copy link

raimonizard commented Jan 10, 2024

Humm, I see...
I would like to have the TOC embedded at the top right in the Gist articles in the same way they appear in the README.md at the regular GitHub repos.

image

Do you know if that's possible?

Example of a Gist article where I would like to have the TOC visible, but otherwise, I had to create it manually through CSS: https://gist.github.com/raimonizard/b91e43f2327dd7bd1554f7f77130c0b4

Thanks!
Raimon

@redonkulus
Copy link
Author

I think you will have to do it manually unless Gist Markup allows for TOC generation. Something I'm not aware of today.

@raimonizard
Copy link

Ok!
Thanks for your time mate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment