Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Animate Scroll to Top JavaScript

I have got 2 websites with the same function. It works on one of the websites, doesn't work on the other.

script.js:

function scrollToTop(){
var timerHandle = setInterval(function() {
  if (document.body.scrollTop != 0 || document.documentElement.scrollTop != 0)
  window.scrollBy(0,-50); else clearInterval(timerHandle); },10);
}

HTML

       <ul class="footer-navigation">
        <li><a class="back" id="backtoTop" onclick="scrollToTop();return false;"href="#">&uarr;Back to Top</a></li>
        <li><a class="home" href="#home">Home</a></li>
        <li><a class="about" href="#about">About</a></li>
        <li><a class="contact" href="#contact">Contact</a></li>
      </ul>

It doesn't hit any error but it seems as though it is "counting". When I console.log it there's a number in the console next to the logged counting but function never executes.

like image 759
RandomDeveloper Avatar asked Dec 20 '25 16:12

RandomDeveloper


2 Answers

Try this:

function scrollToTop(){
  window.scrollTo({top: 0, behavior: 'smooth'});
}
<div style="height: 150vh"> 
scroll down
</div>

           <ul class="footer-navigation">
            <li><a class="back" id="backtoTop" onclick="scrollToTop();return false;"href="#">&uarr;Back to Top</a></li>
            <li><a class="home" href="#home">Home</a></li>
            <li><a class="about" href="#about">About</a></li>
            <li><a class="contact" href="#contact">Contact</a></li>
          </ul>
like image 67
Mohammad Mahdi Kabir Avatar answered Dec 22 '25 08:12

Mohammad Mahdi Kabir


I would say that you shouldn't scroll via a setInterval but through requestAnimationFrame to avoid jankiness in the scroll. A simple solution to your problem would also to use CSS to make your scrolling smooth. However, this affects all scrolling.

function scrollToTop(){
  window.scrollTo(0, 0);
}
html {
  scroll-behavior: smooth;
}
<div style="height: 150vh"> 
scroll down
</div>

           <ul class="footer-navigation">
            <li><a class="back" id="backtoTop" onclick="scrollToTop()"href="#">&uarr;Back to Top</a></li>
            <li><a class="home" href="#home">Home</a></li>
            <li><a class="about" href="#about">About</a></li>
            <li><a class="contact" href="#contact">Contact</a></li>
          </ul>

More about requestforanimationframe:

https://stackoverflow.com/a/46072227/5526624

like image 36
Rickard Elimää Avatar answered Dec 22 '25 08:12

Rickard Elimää



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!