user2840467
user2840467

Reputation: 893

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>

Upvotes: 1

Views: 1154

Answers (1)

rphv
rphv

Reputation: 5537

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>

Upvotes: 1

Related Questions