Skip to content

Instantly share code, notes, and snippets.

@ahmadajmi
Created September 13, 2025 15:50
Show Gist options
  • Save ahmadajmi/8737d843572b34bf3174d2a7ee70afb9 to your computer and use it in GitHub Desktop.
Save ahmadajmi/8737d843572b34bf3174d2a7ee70afb9 to your computer and use it in GitHub Desktop.
<script>
(function () {
// Read the offset your theme computes into CSS
function readOffset() {
const v = getComputedStyle(document.documentElement)
.getPropertyValue('--toc-scroll-offset').trim();
const n = parseInt(v, 10);
return Number.isFinite(n) ? n : 16;
}
function initWithH1() {
if (!window.tocbot) return;
const toc = document.querySelector('.c-table-of-contents__content');
const content = document.querySelector('.c-content');
if (!toc || !content) return;
const offset = readOffset();
try { tocbot.destroy(); } catch (e) {}
tocbot.init({
tocSelector: '.c-table-of-contents__content',
contentSelector: '.c-content',
listClass: 'c-table-of-contents__list',
listItemClass: 'c-table-of-contents__list-item',
linkClass: 'c-table-of-contents__list-link',
headingSelector: 'h1, h2, h3', // include H1
ignoreSelector: '.kg-header-card *, .kg-signup-card *, .gh-post-upgrade-cta *',
scrollSmooth: false,
scrollSmoothDuration: 0,
scrollSmoothOffset: -offset,
headingsOffset: offset,
fixedSidebarOffset: offset
});
}
// Ensure theme bundle (tocbot) has loaded
window.addEventListener('load', function () {
// Try immediately, then gently poll for up to ~5s
if (window.tocbot) return initWithH1();
const started = Date.now();
const timer = setInterval(function () {
if (window.tocbot || Date.now() - started > 5000) {
clearInterval(timer);
if (window.tocbot) initWithH1();
}
}, 80);
});
// Re-init for modal post view (matches theme behavior)
document.addEventListener('modalContentLoaded', function () {
// Run on next frame so modal DOM is in place
requestAnimationFrame(initWithH1);
});
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment