Handling touch events

One of the great things about HTML5 is that you can write one application and it will work on many different devices. Canvas Pad works great as a desktop application where mouse events are available. But it would work just as well on a touch screen device. So let's add support for touch events to the application.

Touch events are similar to mouse events. One difference is that the user can touch the screen with more than one finger, so touch events may contain multiple points. So we will have to take that into consideration when handling them.

There are three basic touch events that browsers support.

  • touchstart: We get this event when the user touches the screen. This is equivalent to the mousedown event.
  • touchmove: We get these events after touchstart when the user moves his/her finger on the screen. This is equivalent to the mousemove event.
  • touchend: We get this event when the user lifts his/her finger off the screen. This is equivalent to the mouseup event.

The touch event object that is passed to the event handler contains an array called touches. This array contains all of the points that were touched. Each object in the touches array has a pageX and a pageY field, just like mouse events.

You can test whether touch events are supported by checking if the document element has an ontouchstart method:

var touchSupported = "ontouchstart" in document.documentElement;

jQuery doesn't include support for touch events, but it would be nice if we could use the same jQuery mechanism to add touch event handlers to elements. So let's write a jQuery extension to add it. We will create a new file called touchEvents.js to put our extension in, so that we can reuse it in other applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.81.94