user2840467 February 2016

Adding scroll speed to function

I have the following code. How would I use setInterval or setTimeout to make the jump from 0px to 500px to happen in 3000ms?

<!DOCTYPE html>
<html>
<head>
<style>
body {
width: 5000px;
}
</style>
</head>
<body>

<p>Click the button to scroll the document window to 500 pixels horizontally.</p>

<button onclick="scrollWin()">Click me to scroll horizontally!</button><br>    <br>

<script>
function scrollWin() {
window.scrollTo(500, 0);
}
</script>

</body>
</html>

Answers


rphv February 2016

Here's one way - divide the number of pixels to move by the amount of time to move in. Use setInterval to move that number of pixels in some fixed length of time inervalTime. Then, cancel the interval when the scroll position reaches the target.

function scrollWin(target, time) {
  var currentPosition = window.pageXOffset || document.documentElement.scrollLeft;
  var scrollInterval = target / time;
  var intervalTime = 10;
  var intervalFunction;
  intervalFunction = setInterval(function() {
    currentPosition = currentPosition + scrollInterval * intervalTime;
    window.scrollTo(currentPosition, 0);
    if (currentPosition >= target) {
      window.clearInterval(intervalFunction);
    }
  }, intervalTime)
}
body {
  width: 5000px;
}
<p>Click the button to scroll the document window to 500 pixels horizontally.</p>

<button onclick="scrollWin(500, 3000)">Click me to scroll horizontally!</button>

Post Status

Asked in February 2016
Viewed 1,108 times
Voted 13
Answered 1 times

Search




Leave an answer