HTML and CSS Reference
In-Depth Information
Handling Touch Events
JavaScript is no slouch when it comes to handling events on the desktop, and
the same can be said for mobile. Events can consist of user-level events (such
as touch and drag), or device-level events (such as orientation changes or
changes in the device's location). The most basic of events are user-level
events. They can be tracked on any DOM element. For mobile devices, there are
four main touch events:
The touchstart event will fire when a user touches an element on the screen.
The touchend event will fire when a user lifts their finger off an element on the
screen after touching it. The touchmove event will track the user's movement,
and fire the event with every movement. The touchcancel event will fire when
the user cancels the touch event by moving outside of the target's bounds and
releasing the screen. This event seems to be unpredictable.
In order to respond to events, you must create event listeners for them using
element.addEventListener(event, callbackfunction); . This method takes the
event name ( touchstart , touchend , etc.) and the callback function. At times, you
might want to prevent the default action for the event from firing. For instance, if
you add an event listener to a link, you might not want the link to open a new
page when it's tapped. To do this, you must add a parameter to the callback
function called e , and call e.preventDefault() at the end of the callback
function. This will also prevent the element from scrolling and interfering with
touchmove events, as shown in the following code snippet.
<div id="touch-plane" style="width: 100%; height: 100%; background: #000000;
color: #FFFFFF;"><span id="coordinates">x: 0 y: 0</span> - <span
id="touching">not touching</span></div>
document.getElementById('coordinates').innerText = 'x: ' +
+ ' y: ' + e.touches[0].clientY;
Search WWH ::

Custom Search