skip to Main Content

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


  1. Chosen as BEST ANSWER
     var scrollToTopBtn = document.querySelector(".scrollToTopBtn");
        var rootElement = document.documentElement;
        
        function handleScroll() {
          // Do something on scroll
          var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight;
          if (rootElement.scrollTop / scrollTotal > 0.8) {
            // Show button
            scrollToTopBtn.classList.add("showBtn");
          } else {
            // Hide button
            scrollToTopBtn.classList.remove("showBtn");
          }
        }
        
        function scrollToTop() {
          // Scroll to top logic
          rootElement.scrollTo({
            top: 0,
            behavior: "smooth" });
        
        }
    
    scrollToTopBtn.addEventListener("click", scrollToTop);
    

    It is better to post the complete code


  2. 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);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search