How can I scroll a div with Zepto.js?

user920041 picture user920041 · May 29, 2012 · Viewed 7.5k times · Source

I have a div with overflow:scroll and I now want to programmatically scroll that div down. Is this possible with Zepto.js?

Answer

Brian Nickel picture Brian Nickel · Jul 5, 2012

An API isn't provided directly by Zepto, but it is accessible from the lower level DOM.

var $el = $('#scrolling-el');
var el = $el[0]; /* Actual DOM element */

/* Scroll to bottom */
el.scrollTop = el.scrollHeight - $el.height();

/* Scroll to top */
el.scrollTop = 0;

Animated scrolling would be a process of using setTimeout. You could write a quick Zepto plugin. Here's a crude example:

$.fn.scrollToBottom = function(duration) {
    var $el = this;
    var el  = $el[0];
    var startPosition = el.scrollTop;
    var delta = el.scrollHeight - $el.height() - startPosition;

    var startTime = Date.now();

    function scroll() {
        var fraction = Math.min(1, (Date.now() - startTime) / duration);

        el.scrollTop = delta * fraction + startPosition;

        if(fraction < 1) {
            setTimeout(scroll, 10);
        }
    }
    scroll();
};