Scrolling to specific Div (or other) ID’s with iScroll 4

Works with PhoneGap
Works with PhoneGap (Photo credit: Brian LeRoux)

A while back I did a little hacking on iScroll 4, which I use quite a bit for PhoneGap based applications (though, it works nice for anything mobile except Windows phones. IE doesn’t like iScroll).

iScroll is becoming a bit less necessary (particularly after iOS 5 was released, which made some changes to mobile Safari), but I still use it for a couple of nice features.  One feature I always feel is lacking – I can’t tell it to specifically scroll to an ID.  I can define an element and do it that way, but it’s not quite as convenient.  So, here’s a quick function at adds scrollToId functionality:


    scrollToId: function (el, time) {
        var that = this, pos;
        el = document.getElementById(el);
        if (!el) return;
        pos = that._offset(el);
        pos.left += that.wrapperOffsetLeft; += that.wrapperOffsetTop;
        pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left; = > that.minScrollY ? that.minScrollY : < that.maxScrollY ? that.maxScrollY :;
        time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(*2) : time;
        that.scrollTo(pos.left,, time);

Pop this between scrollToElement and scrollToPage in iscroll.js.

Yes, I could just do “myScroll.scrollToElement(document.getElementById(“top”))”, but myScroll.scrollToId(“top”) looks a little nicer when I’m whipping through a ton of code looking for something specific. Just a preference thing, really.

I post it here for a funny reason: I upgraded iScroll in a project, and then couldn’t figure out for about 30 minutes why it no longer scrolled properly. And then I had to hunt down my older version of the project… so, as not to loose it again, I popped it on here. Plus, if anyone else is wondering a good way of doing it… well, there you go 🙂

I’m sort of excited to see what the author does with iScroll 5 – I still find myself integrating it into PhoneGap / Cordova projects frequently.

Enhanced by Zemanta

Leave a Comment