0

Maybe it's a stupid question but i want to know why this is not working.

I try to scroll to this element with animation. Normally the element is:

scrollTo(document.body, 0, 100);

I changed the element in a variable named 'here'. If I think logically, the code must scroll to element 'here', to 0px, duration, but i doesn't work. Is there anybody who can tell me whats going wrong?

My code:

document.getElementById('scroll-to-elm').onclick = function () {
var here = document.getElementById('tohere');

    scrollTo(here, 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);
}
  • http://www.w3schools.com/jsref/met_win_scrollto.asp – spectre-d Oct 04 '16 at 16:06
  • Possible duplicate of [jQuery scroll to element](http://stackoverflow.com/questions/6677035/jquery-scroll-to-element), you may not be using jQuery, but what you are asking for is answered in this other question. You should also avoid asking questions such as "why is my code not working/what's wrong with my code". – spectre-d Oct 04 '16 at 16:10
  • Have ypu tried `element.scrollIntoView({behavior: "smooth"});`? [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) – Dimava Oct 04 '16 at 16:14
  • Is there another way for this? I don't wanna use a library like Jquery. What i want is a scroll function with animate time. – Loek Lemmens Oct 04 '16 at 19:30

0 Answers0