ScrollTop to a div instead of body [SOLVED]


#1

Hi.

I have this pure javascript (not want jQuery) to scroll up a page:

 <script type="text/javascript">
document.getElementById('scroll-to-top').onclick = function () {
    scrollTo(document.body, 0, 100);
}

    function scrollTo(element, to, duration) {
        if (duration < 0) return;
        var difference = to - element.scrollTop;
        var perTick = difference / duration * 2;

    setTimeout(function() {
        element.scrollTop = element.scrollTop + perTick;
        scrollTo(element, to, duration - 2);
    }, 10);
}
</script>

But I need it to point at a given div (the first element of a list) and not to the body.

scrollTo(document.body, 0, 100); ????

Can be changed to scroll to the div?

Thanks.


#2

Hi,

Just pass another element instead of document.body into scrollTop() function:

var myDiv = document.getElementById('my-div');
scrollTo(myDiv, 0, 100);

#3
 <script type="text/javascript">
document.getElementById('scroll-to-top').onclick = function () {
var myDiv = document.getElementById('content');
scrollTo(myDiv, 0, 100);
}

    function scrollTo(element, to, duration) {
        if (duration < 0) return;
        var difference = to - element.scrollTop;
        var perTick = difference / duration * 2;

    setTimeout(function() {
        element.scrollTop = element.scrollTop + perTick;
        scrollTo(element, to, duration - 2);
    }, 10);
}
</script>

But it does not work. I am missing something.
?????


#4

My bad, I was completely wrong.
First argument of your scrollTo() function is not where to scroll, but what to scroll.
Second argument defines where to scroll (top offset).
So this should work:

var myDiv = document.getElementById('my-div');
scrollTo(document.body, myDiv.offsetTop, 100);

#5

No, it does not work.


#6

It works
https://jsfiddle.net/mpeymnuv/


#7

Sorry, you are right. It was a mistake of mine.

Thanks and solved.


#8

Sorry pal, but the script does not work as expected.

First, it does not go to the scroll-here div, but to the very top of the page.

Second, I have tested the script in different browsers and seen that it does not work in IE an Firefox. Or perhaps it is a local problem with my computer.

Please have a look.


#9

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.