DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Integration Testing Tutorial: A Comprehensive Guide With Examples And Best Practices
  • How to Optimize CPU Performance Through Isolation and System Tuning
  • Which Is Better for IoT: Azure RTOS or FreeRTOS?
  • Fun Is the Glue That Makes Everything Stick, Also the OCP
  1. DZone
  2. Coding
  3. JavaScript
  4. JavaScript Kinetic Scrolling: Part 1

JavaScript Kinetic Scrolling: Part 1

Ariya Hidayat user avatar by
Ariya Hidayat
·
Dec. 12, 13 · Interview
Like (0)
Save
Tweet
Share
12.02K Views

Join the DZone community and get the full member experience.

Join For Free

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.

related posts:

  • javascript kinetic scrolling: part 3
  • javascript kinetic scrolling: part 2
  • continuous painting mode in chrome
  • optimizing css3 for gpu compositing
  • frame rate hud on chrome for android
JavaScript

Published at DZone with permission of Ariya Hidayat, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Integration Testing Tutorial: A Comprehensive Guide With Examples And Best Practices
  • How to Optimize CPU Performance Through Isolation and System Tuning
  • Which Is Better for IoT: Azure RTOS or FreeRTOS?
  • Fun Is the Glue That Makes Everything Stick, Also the OCP

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: