Skip to content Skip to sidebar Skip to footer

How To Make My Scroll To Top Button Animate Smoothly

I have a scroll to top button on my page, but when I click it, it doesnt scroll to top, it just takes me directly to the top, like as if I loaded a new page, but what I need is the

Solution 1:

Your topFunction() makes a jump to the top of the page. What you actually want is multiple jumps, e.g., going up 20px. And, for it to not occur too fast, add a timeout. I altered your code to make a working example.

Although I would recommend operating with the container div instead of checking for (document.body.scrollTop > step || document.documentElement.scrollTop > step). Setting the element and working with element.scrollTop would be cleaner ( and safer for different browsers ) .

var step = 20;

window.onscroll = function() {
  scrollFunction()
};

functionscrollFunction() {
    if (document.body.scrollTop > step || document.documentElement.scrollTop > step)
    document.getElementById("myBtn").style.display = "block"elsedocument.getElementById("myBtn").style.display = "none"

}

functiontopFunction() {
  if (document.body.scrollTop > step || document.documentElement.scrollTop > step) {
    document.body.scrollTop -= step
    document.documentElement.scrollTop -= step
    setTimeout(function() {
      topFunction()
    }, step)
  } else {
    document.body.scrollTop = 0document.documentElement.scrollTop = 0
  }
}
#myBtn {
  display: none;
  position: fixed;
  bottom: 50px;
  right: 20px;
  z-index: 99;
  border: teal;
  outline: none;
  background-color: #FF6347;
  color: white;
  cursor: pointer;
  padding: 0px;
  border-radius: 100px;
  width: 40px;
  height: 40px;
}

#myBtni {
  width: 40px;
  height: 40px;
  text-align: center;
  z-index: 100;
  line-height: 40px;
  color: white;
}

#myBtn:hover {
  background-color: #FF6320;
}
<divstyle="width:100px;">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit,
  sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
  eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  <buttononclick="topFunction()"id="myBtn"title="Go to top"><iclass="fa fa-angle-double-up"aria-hidden="true"></i></button></div>

Post a Comment for "How To Make My Scroll To Top Button Animate Smoothly"