skip to Main Content

I have a scroll to top button fixed at the bottom-right of my page. When it’s clicked, all I want is to scroll top of the page.

Now, What I tried:

  window.scrollTo(0,0)
  window.scroll({
    top: 0,
    left: 0,
  })
 document.body.scrollTop = 0
  document.documentElement.scrollTop = 0
document.querySelector('header').scrollIntoView({
 behavior: "smooth", block: "start", inline: "nearest"
}) 

all of these works at first but as I scroll down, they scroll up the page a little bit and then stop. they don’t go up.

Why might it be?

PS: I use chrome

2

Answers


  1. Chosen as BEST ANSWER

    Based on @dkellner 's comment I thought that it might related to smooth behavior,

    When I searched it through my css code I found out that I had this line:

    * {
    scroll-behavior: smooth;
    }
    
    

    I changed it to

    html {
    scroll-behavior: smooth;
    }
    

    and problem is solved.

    I know giving all elements scroll-behavior: smooth don't make sense but I really like to know why it causes such an issue.


  2. Use JavaScript to smoothly scroll to the top of the page when the "scroll to top" button is clicked. To prevent interference with the fixed button’s positioning, you can temporarily disable the button’s position: fixed property while scrolling, and then re-enable it afterward.

    const scrollToTopButton = document.getElementById('scrollToTopButton'); 
    
    scrollToTopButton.addEventListener('click', () => {
      scrollToTopButton.style.position = 'static'; 
    
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth',
      });
    
      setTimeout(() => {
        scrollToTopButton.style.position = 'fixed'; // Re-enable fixed positioning after scrolling
      }, 1000); // Adjust the timing as needed
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search