DanielAttard
DanielAttard

Reputation: 3615

Scroll to top animation in pure javascript? Can't use jQuery

Is there an easy way to convert this:

$("html, body").animate({ scrollTop: $(document).height() }, 10000);

into pure javascript? I need to be able to run the js in a setting where I don't have jQuery available. Any ideas? Thanks.

Upvotes: 1

Views: 1201

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32531

You can do so by incrementally changing the scrollTop property over a period of time.

var scrollingElement = document.body;
var endScrollPosition = scrollingElement.clientHeight;
var timeInMS = 10000;
var startTime = new Date().getTime();
var endTime = new Date(new Date().getTime() + timeInMS).getTime() - startTime;

// Use requestAnimationFrame to ensure a smooth transition
requestAnimationFrame(function animate() {
  // Determine what percentage of the total time has passed
  var now = new Date().getTime() - startTime;
  var ratio = now / endTime;
  if (ratio > 1) {
    ratio = 1;
  }
  
  scrollingElement.scrollTop = endScrollPosition * ratio;
  if (ratio < 1) {
    requestAnimationFrame(animate);
  }
});
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>

Upvotes: 1

Related Questions