Reputation: 165
I am trying to animate a "scroll-to-top" button for a div with overflow set to auto (scrollbars are displayed as overflow exceeds div limits, so this is not an issue). On clicking the button i call a for loop in a javascript (not jquery) function. Each descending increment of the for loop (starting at the current element.scrollTop position) is to gradually back the scrolling down until element.scrollTop is 0. Very simple and straightforward in theory. Works like a dream in IE (very atypical!) but DOES NOT WORK in Firefox or Chrome!!!! All it does is JUMPS to the top...no smooth gradual scrolling upward which is what i want! Please help!
javascript:
function scrollUp(d){
var s=document.getElementById(d).scrollTop;
for (x=s; x>0; x=x-1){document.getElementById(d).scrollTop=x;}
}
html:
<div id="this_div" class="container">
<div id="top" class="topbutton" onClick="scrollUp('this_div');">Top</div>
</div>
Upvotes: 0
Views: 2410
Reputation: 1800
you can use timer for animating that
window.onload = function() {
document.getElementById('top').onclick = function() {
scrollUp('this_div');
};
};
function scrollUp(d){
var s = document.getElementById(d).scrollTop;
var scrollDistance = 10;
var scrollSpeed = 200; // 1000 = 1 seconds
var scrollAnimate = setInterval(function() {
if (s > 0) {
s -= scrollDistance;
document.getElementById(d).scrollTop = s;
} else {
clearInterval(scrollAnimate);
}
},scrollSpeed);
}
you can now manipulate the speed and the distance of scrolling by just changing the value of scrollDistance and scrollSpeed.
Upvotes: 1