Home > Software design >  How to make back to the top anchor link smooth scroll
How to make back to the top anchor link smooth scroll

Time:04-22

i'm trying to make the back to the top button on click to be smooth scrolling but i'm stuck.. at the moment this code works but its not smooth scrolling to the top of the page.. can anyone help me on this?

<a id="BackToTop" href="#" title="Back to the top" >
  <span>⌃</span>
</a>
<style>
  .back-to-top {
    position: fixed;
    bottom: 20px;
    right: 25px;
    color: #999;
    background-color: #243066;
    z-index: 60000;  
  }
  .back-to-top span{
     height: 47px;
  }
  .hide {
    display: none!important;
  }
  .back-to-top:hover {
    box-shadow: 1px 1px 25px #9e9e9e;
  }
</style>
<script>
  (function() {
    function trackScroll() {
      var scrolled = window.pageYOffset;
      var coords = 300;

      if (scrolled > coords) {
        goTopBtn.classList.remove('hide');
      }
      if (scrolled < coords) {
        goTopBtn.classList.add('hide');
      }
    }

    function backToTop() {
      if (window.pageYOffset > 0) {
        window.scrollBy(0, -80);
        setTimeout(backToTop, 0);
      }
    }

    var goTopBtn = document.querySelector('.back-to-top');

    window.addEventListener('scroll', trackScroll);
    goTopBtn.addEventListener('click', backToTop);
  })();
</script>

CodePudding user response:

Modern browsers (everything but IE) support a scrollTo method on the window object which you can pass smooth scrolling behaviour to:

window.scrollTo({ top: 0, left: 0, behavior: 'smooth'});

There are also variations on this such as element.scrollIntoView()

CodePudding user response:

You may use that

document.getElementById('id').scrollIntoView({
  behavior: 'smooth'
});
  • Related