Extend Zepto.js with a jQuery method? scrollTop()

matt picture matt · Aug 30, 2012 · Viewed 8.2k times · Source

I'm using Zepto.js on a current project. Zepto doesn't support the scrollTop() method that jQuery has in it.

Is it possible to kind of extend Zepto to work with scrollTop() too?

Update: All I want is to create my own small and simple "animated scroll" function like I have used before with jQuery. See the working example here. However I have no idea how to make the same function work without the scrollTop() function available in Zepto.js.

Answer

callumacrae picture callumacrae · Sep 1, 2012

scrollTop isn't animatable using Zepto's .animate method, as it uses CSS transitions.

Try something like this: http://jsfiddle.net/DVDLM/5/

function scroll(scrollTo, time) {
    var scrollFrom = parseInt(document.body.scrollTop),
        i = 0,
        runEvery = 5; // run every 5ms

    scrollTo = parseInt(scrollTo);
    time /= runEvery;

    var interval = setInterval(function () {
        i++;

        document.body.scrollTop = (scrollTo - scrollFrom) / time * i + scrollFrom;

        if (i >= time) {
            clearInterval(interval);
        }
    }, runEvery);
}

$('#trigger').click(function () {
    scroll('600px', 500);
});

EDIT: I added a runEvery variable, which specifies how often the interval should be ran. The lower this is, the smoother the animation is, but it could affect performance.

EDIT2: I think I misread the question. Here is the answer to the new question:

$.zepto.scrollTop = function (pixels) {
    this[0].scrollTop = pixels;
};