It works in CodePen and in console log snippet: https://codepen.io/MistaPrime/pen/ZEYLvaR
But when inserting it inside of a .js file it gives this error:
Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
The objective of the code is to insert a copy of #numeric-toc
contents after .rounded-block
and create a new div called #sticky-numeric-toc
which will hold the copy of #numeric-toc
contents.
// insert sticky menu holder into the sidebar
var stickyMenu = document.querySelector('.rounded-block');
stickyMenu.insertAdjacentHTML('afterend', '<div id="sticky-numeric-toc">two</div>');
// copy-paste table of contents into sticky sidebar
document.getElementById("sticky-numeric-toc").innerHTML =
document.getElementById("numeric-toc").innerHTML;
// on scroll add fixed class to sidebar
window.addEventListener('scroll', function() {
var elementTarget = document.getElementById('numeric-toc');
if (window.scrollY > (elementTarget.offsetTop + elementTarget.offsetHeight)) {
document.querySelector('#sticky-numeric-toc').classList.add('anotherclass');
} else {
document.querySelector('#sticky-numeric-toc').classList.remove('anotherclass');
}
});
<div id="numeric-toc">
THIS WILL BE CONTENT TO COPY
</div>
<div class="rounded-block">
</div>
Basically my issue is that I cannot make this code work in the browser using a stickysidebar.js which is loaded after the contents. It works on CodePen and snippet but not once the site is launched.
Should I use something other than insertAdjacentHTML
?