Pregunta

this is a simple question. Is there a way in jQuery or Javascript to determine the speed of a touchmove event? I use css to grab the element and make it grabable, this works fine but if I move the finger faster, it's less likely I can move to a threshold distance but I did intend to turn page, so is there a way I can determine the speed of movement on the touch move event in javascript or jQuery, and I can adjust the threshold to a smaller value to compensate the speed?

    var startX, endX, difference, threshold; 
var startTime, endTime, timeDiff = 151;
$('#animate')
.bind("touchstart", function (e){ 
    e.preventDefault();
    var d = new Date();      
    startTime = d.getTime();
    startX = e.originalEvent.touches[0].pageX; //starting point
    })
.bind("touchmove", function (e){
    e.preventDefault();
    endX =e.originalEvent.changedTouches[0].pageX; //Get the information for finger 
    difference = startX - endX;  //calculate the distance moved.
    var moved = minusScreen - difference; //determine the affected css value.
    $(this).css("left",moved);  //this makes the element moves with my finger.
    })
.bind("touchend", function (e) { 
    var date = new Date();
    endTime = date.getTime();
    threshold = Math.abs(difference);
    timeDiff = endTime - startTime;
    if ((threshold > (screenWidth * 0.4)) || (timeDiff < 150))  //make the animation move only when the finger moved more than 30% of the page.
        {           
        if (endX > startX) turnLeft();
        else if (endX == startX) {} // havent decide what to do yet 
        else turnRight();
    } else {
        $(this).animate({"left": minusScreen}, 100);
    }
    startX=0; //set the value back to initial.
    endX=0;   //set the value back to initial.});
    });

thank's for your great answer. the above is modified code. worked great!!!

¿Fue útil?

Solución

get the time on the touchstart and again on touchend like this

startTime = new Date().getTime() and endTime = new Date().getTime()

then calculate var speed = abs(endX-startX)/(endTime-startTime) this is now your overall touchmove speed in px/ms

Otros consejos

Although this is an old question, it seems that there is a "timeStamp" in touch event object, so it might be simpler and faster to simply use :

startTime = e.timeStamp();

in place of :

var d = new Date();      
startTime = d.getTime();

Same thing for var endTime

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top