Reputation: 670
I did some researches on other posts related to swipe functionality and found a useful function however it also affects click events.
Here is the link I found that is swipe function useful: http://www.javascriptkit.com/javatutors/touchevents2.shtml
Is there a way to tweak it and to make click event work.
Here is the sample fiddle http://jsfiddle.net/8rscLo1z/4/ (P.S. Use toggle device toolbar in chrome to work)
Swipe trigger:
var el = document.getElementById('testing_area');
swipedetect(el, function(swipedir){
// swipedir contains either "none", "left", "right", "top", or "down"
if (swipedir =='left'){
$('#testing_area').html('Swipe LEFT detected');
} else if (swipedir == 'right'){
$('#testing_area').html('Swipe RIGHT detected');
} else {
$('#testing_area').html('Swipe UNRECOGNIZED');
}
});
Click event
$('#testing_area').click(function(){
alert('test click');
});
Upvotes: 0
Views: 1853
Reputation:
On your touchend event listener, var distX pertains to the distance travelled by the touch (swipe). You can add additional if condition wherein it will check if distX is equal to 0.
Update you code from:
touchsurface.addEventListener('touchend', function(e){
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX
distY = touchobj.pageY - startY
elapsedTime = new Date().getTime() - startTime
if (elapsedTime <= allowedTime){
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){
swipedir = (distX < 0)? 'left' : 'right'
}
else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){
swipedir = (distY < 0)? 'up' : 'down'
}
}
handleswipe(swipedir)
e.preventDefault()
}, false)
Into this
touchsurface.addEventListener('touchend', function(e){
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX
distY = touchobj.pageY - startY
elapsedTime = new Date().getTime() - startTime
if(distX == 0){
alert('test click'); //this is where click event is detected
} else if (elapsedTime <= allowedTime){
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){
swipedir = (distX < 0)? 'left' : 'right'
}
else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){
swipedir = (distY < 0)? 'up' : '
}
}
handleswipe(swipedir)
e.preventDefault()
}, false)
Here is the working fiddle: http://jsfiddle.net/8rscLo1z/14/show
Upvotes: 1