HTML and CSS Reference
In-Depth Information
Touch position
Like the
utils.captureMouse
function, you can use the
utils.captureTouch
utility to determine the
location of the first finger touch on an element. The two functions are similar, but because there might not
be a finger touching the screen, the property
isPressed
has been added to the returned object. This
property contains a Boolean value indicating whether a touch is detected. Also, when there is no active
touch present, the properties
x
and
y
are set to
null
. Add the following function to the
utils.js
file:
utils.captureTouch = function (element) {
var touch = {x: null, y: null, isPressed: false};
element.addEventListener('touchstart', function (event) {
touch.isPressed = true;
}, false);
element.addEventListener('touchend', function (event) {
touch.isPressed = false;
touch.x = null;
touch.y = null;
}, false);
element.addEventListener('touchmove', function (event) {
var x, y,
touch_event = event.touches[0]; //first touch
if (touch_event.pageX || touch_event.pageY) {
x = touch_event.pageX;
y = touch_event.pageY;
} else {
x = touch_event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = touch_event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= offsetLeft;
y -= offsetTop;
touch.x = x;
touch.y = y;
}, false);
return touch;
};
The function definition is similar to the mouse position version, but with a few extra event listeners. It takes
an element argument and returns an object with properties
x
,
y
, and
isPressed
. The
touchmove
event
handler keeps track of the position of the first touch relative to the element, using some cross-browser
code to calculate the offset. There are also also event handlers added for
touchstart
, which sets
isPressed
to
true
, and
touchend
, which sets
isPressed
to
false
. It also sets the
x
and
y
properties to
null
, because there is no longer an active position.
You can initialize the
touch
object like before: