IamGuest IamGuest - 8 days ago 6
Javascript Question

Create a nice scrolling/sliding effect with JS

I would like to create a "smooth" scroll animation that slides down from one element to the next. I do not want to use Jquery or any libraries, just javascript and HTML. I have tried:

element.scrollIntoView();


This causes scrolling, but not a smooth animation. I have already looked at some other smooth-scrolling techniques, but they use Jquery. I would also like to add that the scrolling should be from ELEMENT on a page to another ELEMENT on the page. Scroll down only. Also only javascript function like
function scrollFromHere(from, to)
.

Answer

Never mind, I think I found an answer to my question. It took lots of searching, but here it is:

<div id="elem1"><button onclick="scrollToward('elem2', 'elem1');">Scroll Down</button></div>
<div id="elem2"></div>

<script>
//Here is my script:
function animate(elem,style,unit,from,to,time,prop) {
    if( !elem) return;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);
            if (prop) {
                elem[style] = (from+step*(to-from))+unit;
            } else {
                elem.style[style] = (from+step*(to-from))+unit;
            }
            if( step == 1) clearInterval(timer);
        },25);
    elem.style[style] = from+unit;
}

    function scrollToward(ele, from) {
    var target = document.getElementById(ele);
    from = document.getElementById(from).offsetTop;
    animate(document.body, "scrollTop", "", from, target.offsetTop, 1500, true);
}
</script>

Tested and works when you style the divs in a way that creates a scrollbar. Found the answer here.

Comments