Hkan Hkan - 3 months ago 17
Javascript Question

Handling Velocity/Inertia on Dragging

I've built a vertical sliderish thing in my web application with the support of mouse and touch dragging events by Hammer.js. At the end of the drag (when user releases mouse button or takes his finger off the screen, a.k.a

dragend
event), if the one above is closer to middle, it gets moved to the middle and vice versa.

The thing is, when dragend event is triggered at %48 when user drags the mouse from down to up (which means the one above will get moved to middle) if the velocity is high enough, the one below should get moved to middle. How to calculate if the velocity is high enough?

Answer

I solved it like this:

// y is the drag amount

// visible height
var height = $(this).height()

// difference
var diff = (Math.abs(y) % height) / height

// I checked Hammer.js's source. It defines velocity as the change in 16ms.
// So multiplying it by 62.5 gives you the change in 1s. 
// Not sure why I did that, but works pretty well in most situations
var inertia = event.gesture.velocityY * 62.5

if (
    (event.gesture.direction == 'up' && diff + (inertia / height) >= 0.5) ||
    (event.gesture.direction == 'down' && diff - (inertia / height) >= 0.5)
) {

    // show the one below

} else {

    // show the one above

}