JSFiddle - React, Tailwind, and code Playground
by blineberry
HTML
<div class="control"><label for="distance">Distance Threshold:</label> <input id="distance" type="text" value="30" />px</div>
<div class="control"><label for="time">Time Threshold:</label> <input id="time" type="text" value="1000" />ms</div>
<div id="target" unselectable="on" >Swipe Me</div>
<div class="output"><label for="distanceAct">Distance Traveled:</label> <input id="distanceAct" type="text" readonly />px</div>
<div class="output"><label for="timeAct">Time Taken:</label> <input id="timeAct" type="text" readonly />ms</div>
CSS
html, body {
height: 100%;
font: 12px/1.5 sans-serif;
}
.control, .output {
margin: 0.5em auto;
width: 90%;
}
label {
display: inline-block;
min-width: 130px;
}
#target {
width: 90%;
height: 300px;
margin: 1em auto;
border: 1px solid silver;
text-transform: uppercase;
line-height: 300px;
text-align: center;
font-size: 5em;
color: silver;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
JavaScript
var is_touch_device = 'ontouchstart' in document.documentElement;
if (!is_touch_device) {
$('#target').text('Device does not support touch.').css('line-height','1.2');
}
$('#target').on('touchstart', function(e) {
document.ontouchmove = function(e){ e.preventDefault(); }
var touch = e.originalEvent.touches[0];
var startX = touch.pageX;
var startY = touch.pageY;
var target = $(this);
var targetWidth = target.width();
var targetHeight = target.height();
var startTime = new Date().getTime();
var distanceThreshold = parseInt($('#distance').val(), 10);
var timeThreshold = parseInt($('#time').val(), 10);
var swipeTimeout = window.setTimeout(function() {
document.ontouchmove = function(e){ return true; }
}, timeThreshold);
$(document).one('touchend', function(e) {
window.clearTimeout(swipeTimeout);
var endTouch = e.originalEvent.changedTouches[0];
var endX = endTouch.pageX;
var endY = endTouch.pageY;
var endTime = new Date().getTime();
if (endTouch.target == target.get(0)) {
if (endTime - startTime <= timeThreshold) {
var diffX = endX - startX;
var diffY = endY - startY;
if (Math.abs(diffX) >= distanceThreshold || Math.abs(diffY) >= distanceThreshold) {
target.trigger('swipe');
}
if (Math.abs(diffX) > Math.abs(diffY)) {
$('#distanceAct').val(Math.abs(diffX));
}
else {
$('#distanceAct').val(Math.abs(diffY));
}
}
$('#timeAct').val(endTime - startTime);
}
document.ontouchmove = function(e){ return true; }
});
});
$('#target').on('swipe', function() {
$(this).text('Swiped!');
window.setTimeout(function() {
...