Skip to content

Instantly share code, notes, and snippets.

@yuliyang
Created January 26, 2022 08:22
Show Gist options
  • Save yuliyang/63a887b255af31ae87be927286e6f219 to your computer and use it in GitHub Desktop.
Save yuliyang/63a887b255af31ae87be927286e6f219 to your computer and use it in GitHub Desktop.
[HelpScout] Turn H2 to Table of Content
<!-- Insert into your article (switch to HTML mode) -->
<section class="index-list">
<h4>In This Article</h4>
<ul id="toc"></ul>
</section>
<!-- This script will load all H2 headings in your article -->
<h2>I am a title!</h2>
<!-- Insert into code field at Manage > Docs > [Your Docs Site] > Custom Code > Insert <head> Code -->
<script type="text/javascript">
(function() {
function tocScript() {
var articleWrap = $("article#fullArticle");
var ul = $("ul#toc");
if( articleWrap && ul ) {
articleWrap.find("h2").each(function( index ){
var title = $(this).text();
var link = title.toLowerCase().replace(/[^a-z0-9\-_]+/g, "-").replace(/-{2,}/, "-").replace(/^-|-$/, '');
var number = index + 1;
$(this).attr('id', link);
var item = $('<li><a href="#' + link + '">' + number + ". " + title + '</a></li>');
ul.append(item);
});
}
}
if (window.addEventListener) {
window.addEventListener("load",tocScript,false);
} else if (window.attachEvent) {
window.attachEvent("onload",tocScript);
}
})()
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment