How to set timer for the follwing scroll to top function

Viewed 387

I have the following simple scrollTop() function obtained from w3schools. The issue i have is setting the time for scrolling. Different people gave different methods and everyone removed one or all lines from the following code. I'm waiting for a function which can be added to set the scrolling speed and no other text is to be removed. Here's the codepen work https://codepen.io/vkdatta27/pen/zYqQbmM

var mybutton = document.getElementById("myBtn");

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

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    mybutton.style.display = "block";
  } else {
    mybutton.style.display = "none";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 20px;
}
#myBtn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  font-size: 18px;
  border: none;
  outline: none;
  background-color: red;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}
#myBtn:hover {
  background-color: #555;
}
html {
  scroll-behavior: smooth
}
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible
  <strong>when the user starts to scroll the page</strong></div>

1 Answers

Remove the function topFunction of your onclick="topFunction()" this no good pratic, and add event listener to click button calling function to exec this code:

mybutton.addEventListener("click", scrollTime);

async function scrollTime() {
    var time = 5; //seconds
    var y = document.documentElement.scrollTop; //get y position of scroll
    var duration = y/time; //calcule duration steps 
    while(y>0)
    {
        y = y-duration; //subtract by duration
        window.scrollTo({top: y, behavior: 'smooth'}); //move to position y
        await new Promise(res => setTimeout(res, 1000)); //await function with 1000 ms by steps
    }
}
Related