Skip to content

Instantly share code, notes, and snippets.

@burhanuddin7
Created November 8, 2022 11:38
Show Gist options
  • Save burhanuddin7/6928b4cb3e11e87b42ad8e456c3ddb6e to your computer and use it in GitHub Desktop.
Save burhanuddin7/6928b4cb3e11e87b42ad8e456c3ddb6e to your computer and use it in GitHub Desktop.
var tocJS = (function () {
function init() {
uiBindings();
}
var uiBindings = function () {
var parentHeading = document.querySelector('.main-page-content'), // main content
parentBlock = document.querySelector('toc list parent div'),
tocBlock = document.querySelector('TOC block parent class'),
allHeading = parentHeading.querySelectorAll('h2, h3, h4'),
dataList = '<ul>',
startTocNested = false;
if (!tocBlock) {
return false;
}
// retrun if heading list is less than 3 or greater than 10
if(allHeading.length < 3 || allHeading.length > 10) {
tocBlock.remove();
return false;
}
for (var i = 0; i < allHeading.length; i++) {
var clearInnerHeading = allHeading[i].innerHTML.replace(/\n|<.*?>/g,'');
if (allHeading[i].nodeName == 'H2' || allHeading[i].nodeName == 'H3') {
if(clearInnerHeading) {
if (startTocNested) {
dataList += '</ul>';
startTocNested = false;
}
if (i == 0) {
dataList += '<li><a class="cta-scroll" href="#toc0">' + clearInnerHeading;
allHeading[i].setAttribute("id", "toc0");
} else {
dataList += '</a></li><li><a class="cta-scroll" href="#toc' + i + '">' + clearInnerHeading;
allHeading[i].setAttribute("id", "toc" + i);
}
}
}
if (allHeading[i].nodeName == 'H4') {
if(clearInnerHeading) {
if (!startTocNested) {
dataList += '<ul>';
startTocNested = true;
}
dataList += '<li><a class="cta-scroll" href="#toc' + i + '">' + clearInnerHeading + '</a></li>';
allHeading[i].setAttribute("id", "toc" + i);
}
}
}
dataList += '</a></li></ul>';
parentBlock.innerHTML = dataList;
// Remove unwanted anchor tag
var anchors = parentBlock.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if(anchor.innerHTML == "") {
anchor.parentNode.removeChild(anchor); //removes the anchor
}
}
// Smooth Scroll
var ctaScroll = document.querySelectorAll(".cta-scroll");
for (var j = 0; j < ctaScroll.length; j++) {
if(ctaScroll[j]) {
ctaScroll[j].addEventListener("click", navScroll);
}
}
function navScroll(e) {
e.preventDefault();
var href = this.getAttribute("href"),
headerNavElem = document.getElementById("header-habitat"),
headerHeight = headerNavElem ? headerNavElem.offsetHeight - 21 : 0,
catHeaderElem = document.getElementById("guide-cat-nav"),
catHeaderHeight = catHeaderElem ? catHeaderElem.offsetHeight : 63,
offsetTop = document.querySelector(href).offsetTop - (headerHeight + catHeaderHeight);
bsLib.scrollIt(
offsetTop,
1000
);
}
// Place TOC before first h2 or h3
var firstheading = document.getElementById("toc0");
firstheading.parentNode.insertBefore(tocBlock, firstheading);
};
init();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment