bootstrap-toc
bootstrap-toc copied to clipboard
TOC adjusts margin with sticky-top header
Many thanks for this very useful extension. I have successfully implemented it with my own site following your instructions, with just one caveat.
I have a bootstrap header with sticky-top header. Right now the #toc also has a sticky-top, but is basically fixed to the left of the screen. What is happening now is that the #toc will be very close to the header initially, but will look good once the header disappears.
Can I make the #toc relative to the header, scroll with the body, and stay once the header disappears? The github summary page has a similar behavior in which the left "box" moves with the page until the header disappears.
I "solved" the problem by monitoring the scroll event that affect the location of the header, the code is like
document.addEventListener('scroll', e => {
let hr = document.getElementById('sticky_header').getBoundingClientRect();
let top = hr.y < 0 ? Math.max(hr.height + hr.y, 0) + 42 : hr.height + 42;
document.getElementById('toc').style.top = `${top}px`;
});
which means,
- If
y >= 0, the header is still present, settoptoheight + 42. - Otherwise if
height + y > 0, it is in the middle of scroll, set toctoptoheight + y + 42. - If
height +y <= 0, the header is moved out of view, set toctopto42.
I do not really need the "scroll with header" feature and I generally dislike monitoring scroll due to performance considerations. I would appreciate it if anyone can recommend perhaps a pure css solution.