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="#">↑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.
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="#">↑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>
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="#">↑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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With