I have coded a smooth scroll to top button JS shown here:
mybutton = document.getElementById("btnTop");
// When the user scrolls down 20px from the top of the document, show the button.
// This can be modified!
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
// document.body.scrollTop = 0; // For Safari
// document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
window.scrollTo({ top: 0, behavior: 'smooth' });
}
with the rest of the code being CSS for visuals and an HTML callout and it was working just fine until I had to use a getBoundingClientRect to get the DOM to detect the active state of the current section on the page. Code Shown here
window.onscroll = function() {
document.querySelectorAll("section").forEach(function(active) {
let activeLink = navBar.querySelector(`[data-nav=${active.id}]`);
if(active.getBoundingClientRect().top >= -400 && active.getBoundingClientRect().top <= 150){
active.classList.add("your-active-class");
activeLink.classList.add("active-link");
}
else{
active.classList.remove("your-active-class");
activeLink.classList.remove("active-link");
}
});
}
and since then my button disappeared, i would say it has something to do with the window.onscroll function. how do i fix this while keeping both codes?