Reputation: 8070
I recently tried to make the scroll to top with animate jquery. Everything seems ok. But I need to do as with percentage.
For Example
scrollTop
is 100%
then it scroll's 100% . I am not sure. Right now i believe it is in pixel. How to use percentage in animate function of jquery, something like scrollTop:100%
I tried that but i get console error.
Here is the fiddle
$('#spnTop').on("click",function(){
$('html,body').animate({ scrollTop: 0 }, 'slow', function () {
alert("reached top");
});
});
Upvotes: 1
Views: 613
Reputation: 78525
As you say, the scrollTop height is in pixels. From the docs:
An integer indicating the new position to set the scroll bar to.
You would have to calculate the percentage yourself:
$('#spnTop').on("click",function(){
var percentageToScroll = 0.50;
var documentHeight = $(document).height();
var scrollAmount = Math.floor(documentHeight * percentageToScroll);
$('html,body').animate({ scrollTop: scrollAmount }, 'slow', function () {
alert("reached top");
});
});
Upvotes: 2
Reputation: 1074168
Since, as you found, animate
requires a pixel value, you'll have to take the height of the element (innerHeight
is probably best), apply the percentage to it (Math.round(height * percentage / 100)
assuming a percentage
value like 70
for 70%), and then use that number of pixels.
Upvotes: 2