Accessing touch events with Javascript on an iOS device or simulator

Following on from the quick tip on how to test websites across iOS devices without an iOS device, this is a really quick post containing the code to display a very simple monitor of touch events. I hope it helps.
<!DOCTYPE html><head>
<script> 

// Set public variables that can be accessed from all functions
var touch;
var startTouchX;
var startTouchY;

// add function on touchstart event to tell us where the touches started

function movementStart(event) {
    event.preventDefault();
    touch = event.touches[0];
startTouchX = touch.pageX;
startTouchY = touch.pageY;
    document.getElementById("start").innerHTML="Touches Started at the Co-ordinates x:" + startTouchX + ", y:" + startTouchY;
}

// add function on touchmove event to tell us where the touches currently are

function movement(event) {
    event.preventDefault();
touch = event.touches[0];
    document.getElementById("position").innerHTML="Live Touch Co-ordinates x:" + touch.pageX + ", y:" + touch.pageY;
}

// add function on touchend to tell us the final position and the length and height of the change
function movementEnd(event) {
document.getElementById("end").innerHTML="Touches Ended at the Co-ordinates x:" + touch.pageX + ", y:" + touch.pageY +" and travelled a length of " + (touch.pageX - startTouchX) + " pixels and height of " + (startTouchY - touch.pageY) + " pixels";

}

// add listeners to page when function is called onload of body so that the above functions will be called

function listenMovement() {
document.addEventListener('touchmove', movement, false);
document.addEventListener('touchstart', movementStart, false);
document.addEventListener('touchend', movementEnd, false);

}

</script>
</head>
<body onload="listenMovement();">
<div>
<h1>Touch the screen and follow your co-ordinates on an iOS device or simulator</h1>
<h2 id="position">Live Touch Co-ordinates x: , y:</h2><h3 id="start">Touches Started at the Co-ordinates x: , y:</h3>
<h3 id="end">Touches Ended at the Co-ordinates x: , y:</h3>
<p><i>If you are using this page in the iOS Simulator program with a multitouch Trackpad / Magic Trackpad use a three-finger swipe. To simulate the touch event with a mouse or other device click and move simultaneously.</i></p></div></body></html>

Comments