I am using Anchorjs with Bootstrap scrollspy (or at least trying to!).
AnchorJS adds id to each element on DOMContentLoaded
:
document.addEventListener('DOMContentLoaded', function (event) {
const anchors = new AnchorJS();
anchors.add('.post h2:not(:empty), .post h3:not(:empty), .post'
+ ' h4:not(:empty), .post h5:not(:empty), .post h6:not(:empty),'
+ ' .post p:not(:empty)');
anchors.options = {icon: '#'};
});
ScrollSpy is initiated after complete
readystatechange
:
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
const scrollSpyContentEl = document.getElementById('body')
const scrollSpy = bootstrap.ScrollSpy.getOrCreateInstance(scrollSpyContentEl, {
target: '#anchor-list',
offset: 36,
}) // Returns a Bootstrap scrollspy instance
}
});
However, I still get an a Uncaught DOMException
:
Failed to execute 'querySelector' on 'Document': '#example-anchor' is not a valid selector.
This is presumably because document.getElementById('body')
does not include the IDs set by AnchorJS.
How can I fix this? scrollspy.refresh()
makes no difference.