.

Tags:

Flick list, with its momentum effect and elastic edge, becomes a common user-interface pattern since it was made popular by Apple iPhone a few years ago. Implementing this pattern using HTML and JavaScript seems to be a daunting task for many web developers. In this series, I will uncover the mystery of kinetic scrolling via several easy-to-digest code examples.

Before we go crazy and apply those fancy effects, it is important to set a solid foundation. Hence, the first part will deal only with an exemplary implementation of a basic drag-to-scroll technique (no momentum, no edge bouncing). The concept and also some parts of the code will be reused in the rest of the series. If you want to follow along and get the full code, check out the repository github.com/ariya/kinetic.

scroll

Here is the game plan. Let us assume that the view (a DOM element) we want to scroll is quite large. Being viewed on the limited device screen, it is as if the screen acts as a viewport window. Scrolling the content is a matter of translating the view while keeping the viewport fixed. In order to translate the view correctly (using CSS3 transform), we need to capture the user interaction with the view. As the user taps and then drags up/down the view, we need to control the offset accordingly to give the illusion that the view follows his finger’s movement.

For this tutorial, the view contains the common Lorem ipsum text (generated via lipsum.com). Also notice that the scrolling is only in the vertical direction. To give an idea, try to load the demo ariya.github.io/kinetic/1 on your modern smartphone. It has been tested on Android 4.3 (Chrome, Firefox), Android 2.3 (Kindle Fire), and iOS 6 (Mobile Safari).

basicscroll

Since we do not want the browser to handle and interpret user gesture natively, we need to hijack it. This is achieved by installing the right event listeners (for both mouse and touch events), as illustrated below. The handlers tap, drag, and release have the most important role in the implementation of this scrolling technique.

view = document.getElementById('view');
if (typeof window.ontouchstart !== 'undefined') {
    view.addEventListener('touchstart', tap);
    view.addEventListener('touchmove', drag);
    view.addEventListener('touchend', release);
}
view.addEventListener('mousedown', tap);
view.addEventListener('mousemove', drag);
view.addEventListener('mouseup', release);

Initializing some state variables is also an important step. In particular, we need to find the right bounds (max and min) for the view’s scrolling offset. Because our view will occupy the whole screen, innerHeight is used here. In a real-world application, you might want to use the computed (style) height of the view’s parent element instead. As you will see shortly, pressed state is necessary to know when the user drags the list.

max = parseInt(getComputedStyle(view).height, 10) - innerHeight;
offset = min = 0;
pressed = false;

If you try the demo, you will notice a subtle scroll indicator. Intentionally, this is placed on the left side of the view. This way, you will notice immediately that this is not the browser’s native scrollbar. That indicator needs to be placed anywhere between the topmost and bottommost of the screen, hence the need for a relative factor (will be used later). Bonus point: where does that hardcoded value 30 comes from?

indicator = document.getElementById('indicator');
relative = (innerHeight - 30) / max;

Since we want to adjust the view’s position using CSS3 transform, we need to figure out the right style property to use. A comprehensive detection can be employed, but the following simple approach already works quite reliably.

xform = 'transform';
['webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
    var e = prefix + 'Transform';
    if (typeof view.style[e] !== 'undefined') {
        xform = e;
        return false;
    }
    return true;
});

Before we see the actual event handlers, let us take a look at two important helper functions.

Since both mouse and touch events need to be supported, the following ypos function abstracts the retrieval of the vertical position associated with the event.

function ypos(e) {
    // touch event
    if (e.targetTouches && (e.targetTouches.length >= 1)) {
        return e.targetTouches[0].clientY;
    }
 
    // mouse event
    return e.clientY;
}

Another important function is scroll, it moves the view and the scroll indicator to the right place. Note that we need to clamp the scroll offset so that it does not go outside the computed bounds.

function scroll(y) {
    offset = (y > max) ? max : (y < min) ? min : y;
    view.style[xform] = 'translateY(' + (-offset) + 'px)';
    indicator.style[xform] = 'translateY(' + (offset * relative) + 'px)';
}

All good things come in three. The functions tap, release, and drag are essential to the core logic of the scrolling. Surprisingly, they are all simple and concise!

The first one, tap, is triggered when the user touches the list for the first. This is where we need to mark it as pressed.

function tap(e) {
    pressed = true;
    reference = ypos(e);
    e.preventDefault();
    e.stopPropagation();
    return false;
}

Later on, when the user releases his grip, we need to undo the marking via release.

function release(e) {
    pressed = false;
    e.preventDefault();
    e.stopPropagation();
    return false;
}

Every time the user moves his finger, we know exactly how many pixels it has moved (since we always track the last point). This way, the view's offset also receives the same amount of relative scrolling movement. A simple threshold of 2 pixels is used to prevent jittering due to some micromovements.

function drag(e) {
    var y, delta;
    if (pressed) {
        y = ypos(e);
        delta = reference - y;
        if (delta > 2 || delta < -2) {
            reference = y;
            scroll(offset + delta);
        }
    }
    e.preventDefault();
    e.stopPropagation();
    return false;
}

And that's all the scrolling code! Overall, it weighs just around 80 lines.

Feel brave and want an exercise? Tweak the scroll indicator so that it fades in and fades out at the right time (synchronized with the pressed state). Its opacity can be animated with CSS3 transition.

Also, keep in mind that the code presented here serves mostly as an inspiration. It is optimized for readability and not for performance (extreme JavaScript optimizations, GPU compositing, etc). Your real-world implementation needs to be more structured, robust, and well-tested.

scrollframes

How about the performance? Well, at this stage, there is hardly anything computationally expensive. The scrolling speed can be checked either using Chrome's frame rate HUD or painting time. More detailed timeline is also available via Chrome Developer Tools. The above capture shows the frame statistics on a Nexus 4 running Chrome 28. We are well within the limit of 60 fps!

In the next installment, watch how the momentum effect gets implemented. Stay tuned.
Update: I already published the second part, covering the physics behind the inertial deceleration.

  • Matthew Kastor

    I like that you’ve provided people with an implementation, using web standards, that they can utilize to get this effect but, it doesn’t translate well for mouse and touchpad use. When I say touchpad I mean the device built into my laptop, not a tablet, not a touchscreen. I’m sure you know what I mean but other people get confused because of the word “touch”.

    Anyway, I like being able to highlight text on the screen for copying, pasting, and also have several options in my context menu for researching the current text selection. I’ve tried your demo and notice that there is no way for me to highlight text by clicking and dragging. It really pisses me off when websites hijack my mouse events like this. Also, on my touchpad I have an emulated mousewheel. By running my finger down the right edge of the touchpad I can already scroll the page but in you demo this doesn’t work because you’ve captured the event. Bad. Very bad. There are many articles on the web about why you shouldn’t hijack the mouse unless it’s necessary. Google docs is an example of when it’s necessary to hijack the right click. I can’t think of any time when I’d find this “drag by pointer” effect useful while using my mouse or touchpad though.

    • http://ariya.ofilabs.com/ Ariya Hidayat

      I appreciate your feedback. As I’ve written as a disclaimer in the blog post, this tutorial should serve as an inspiration only. Think of it like the usual exercises/mid terms in your engineering courses. Nothing in those exercises suggest that you should tackle the problem in the same way (or with the same assumptions and boundaries) in a real-world application. An example is an example, it is meant to be didactic.

      • Matthew Kastor

        Where is the disclaimer? I respect you immensely and think you’re some kind of genius for real. I don’t want you to feel like I’m trying to make you angry or call you stupid in any way shape or form. I didn’t see this disclaimer about how it would be a bad idea to implement this in a website as is, and should be modified to affect only touchscreen users.

        • http://ariya.ofilabs.com/ Ariya Hidayat

          It is near the end, look for the word “inspiration”.

          • Matthew Kastor

            XD Well you got me there! Love the italics. :D

          • http://ecmazing.com/ Šime Vidas

            Disclaimers should be at the very top of the blog post and should start with **Disclaimer:** (or a similar label) IMO.

          • http://ariya.ofilabs.com/ Ariya Hidayat

            This wasn’t meant to be an explicit disclaimer.

    • kartofelek007

      This is very interesting problem. For example i have page with slides. I should allow to slide this app with gestures? Or maybe i should allow to mark text?

      What about this all js plugins for simulate gestures?

  • volken

    i’m looking forward for part 2!

  • dTb

    I am also looking forward the part 2 :) !

  • Steve

    Thanks for this well written article. Is part 2 still coming? I can’t wait!

    • http://ariya.ofilabs.com/ Ariya Hidayat

      Your patience will be rewarded :)

  • Victornpb

    You can’t use the trackpad of a macbook to scroll the page without clicking, and you just broke OSX natural scrolling

    • http://ariya.ofilabs.com/ Ariya Hidayat

      That’s intentional. I mean, who would deploy an example code intended for instructional purposes in a production-grade facility?

  • qmacpit

    where on earth is the part 2? :P looking forward to it….many thanks for part 1

  • Riyadh Al Nur

    awesome write up

  • Никита Гаврилов

    I wonder why you decided to use “translate” rather than “scrollTop” of “style.top”, which work cross-browser.
    Anyways thanks for sharing the script!

  • Michał Gołębiowski

    Nice writeup! One nit: your code prefers prefixed transform to unprefixed one, you should have an empty string at the beginning.

    BTW, the Moz and O prefixes are long not needed.

  • http://getmoneymakemoney.com/ Dmitry Minkovsky

    Really nice. Thank you.