I am trying to capture the duration elapsed between touch start and end, and cant seem to get a consistent behavior no matter what I try.
I have tried a few different solutions, but the behavior is always sporadic. Here is an example of what I am currently trying(below).
I have alerts in place for the long and short touch, but there just seems to be no consistency in the result.
I do see a similar question has been asked here before ‘get-the-duration-of-a-touch-in-javascript’ but that solution produces the same uncertain results.
Any advise would be really appreciated.
$(document).ready(function() {
var $IndividualItem = $(".wrapperWithHover li a");
var touchStartTime;
var touchStartLocation;
var touchEndTime;
var touchEndLocation;
$IndividualItem.bind('touchstart', startOfTouch);
$IndividualItem.bind('touchend', endOfTouch);
$IndividualItem.bind('touchmove', endOfTouch);
function startOfTouch(e) {
e.preventDefault();
var d = new Date();
touchStartTime = d.getTime();
}
function endOfTouch(e) {
e.preventDefault();
var d = new Date();
touchEndTime= d.getTime();
doTouchLogic();
}
function doTouchLogic() {
var duration = touchEndTime - touchStartTime;
if (duration <= 1500) {
alert('1');
}
if (duration > 1500) {
alert('2');
}
duration = null;
}
$('.wrapperWithHover li a').each(function() {
var timeout,
longtouch;
$(this).bind('touchstart', function() {
timeout = setTimeout(function() {
longtouch = true;
}, 1000);
}).bind('touchend', function() {
if (longtouch) {
// It was a long touch.
}
longtouch = false;
clearTimeout(timeout);
});
});
});
here is a small snip of html I’m using for testing.(had to remove the a hrefs as stackoverflow prevented me from submitting the question with them there.)
- test
- test
- test
You don’t have to capture the
touchmoveevent. Because of thatendOfTouchmethod is called ontouchmoveevent before eventouchendhas happened.Remove this line from your code and try. It should give you proper result.