0

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

While your answer does in fact work, (thank you), it seems that maybe I am missing a "bug" with firefox/chrome, and this is what I really want to find a way to work around. This method seems to kind of be a "duct tape over the hole" method. Please don't mistake me for being ungrateful.
i edited the code i added something now and remove the inline onclick = scrollUp('this_div') in your div. its not realiable sometimes. try it
The function is triggering - already debugged that. In FF and Chrome it isn't "smoothly" scrolling up the page to the top, just jumping, just like a regular anchor link would do. IE does it fine.
did you already use a reset.css? not all browser has same compatibilities in css. maybe that would help.
Anyone???? I've seen quesions a lot dumber than this receive more than one answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.