Question

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 dragendevent), 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?

Was it helpful?

Solution

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

}

OTHER TIPS

In Microsoft's WPF (now open-source), the inertial velocity is based on a weighted moving average of the last several position values (with their associated timestamps).

See ManipulationSequence.cs and the OnCompletedManipulation() method (presently starting on line 558). The velocities for translation (i.e. X and Y), expansion, and rotation are calculated based on a rolling history of timestamped values, in the CalculateWeightedMovingAverage() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top