I have a problem and that is I have a back to top button but when I click on it it doesn’t work
<button class="scrollToTopBtn showBtn">☝️</button>
function scrollToTop() {
// Scroll to top logic
rootElement.scrollTo({
top: 0,
behavior: "smooth"
});
}
scrollToTopBtn.addEventListener("click", scrollToTop);
document.addEventListener("scroll", handleScroll);
Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)
It’s bugging this line and I expect it to work
scrollToTopBtn.addEventListener("click", scrollToTop);
And I expect the back to top button to work
2
Answers
It is better to post the complete code
You seem to need to use
document.querySelector()
. You cannot simply type a elements class name in Javascript. You have to select the element.Change this line:
scrollToTopBtn.addEventListener("click", scrollToTop);
To this:
document.querySelector(".scrollToTopBtn").addEventListener("click", scrollToTop);