Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: How does event.touches property work?

I don't understand how to use the event.touches property. For example to get the number of fingers on a iPad/iPhone you should use

event.touches.length

Then why is this example code not working?

$('.image').bind('touchstart', function(event) {
  alert(event.touches.length);
});

But this is working:

$('.image').bind('touchstart', function() {
  alert(event.touches.length);
});

Shouldn't it be the other way round?

like image 786
Tina Avatar asked Nov 01 '11 11:11

Tina


People also ask

What is touch events in JS?

Touch events consist of three interfaces ( Touch , TouchEvent and TouchList ) and the following event types: touchstart - fired when a touch point is placed on the touch surface. touchmove - fired when a touch point is moved along the touch surface. touchend - fired when a touch point is removed from the touch surface.

How do I use Touchmove event?

The touchmove event occurs when the user moves the finger across the screen. The touchmove event will be triggered once for each movement, and will continue to be triggered until the finger is released. Note: The touchmove event will only work on devices with a touch screen.

What is touch event in HTML?

The event occurs when a finger is removed from a touch screen. ontouchmove. The event occurs when a finger is dragged across the screen. ontouchstart. The event occurs when a finger is placed on a touch screen.

What is touch cancel?

The touchcancel event is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).


1 Answers

In the second case, you're falling back on the browser's global (and raw) event object rather than the jQuery-specific one (on browsers that support a global event, not all do — Firefox doesn't, for instance — because it's a Microsoft thing only some others have copied).

It sounds like jQuery isn't passing the touches property on in its custom event object. As described in the event object's documentation, you can use event.originalEvent in your first example to access the "special properties" it has while still getting the benefits of the jQuery normalized event object, e.g.:

$('.image').bind('touchstart', function(event) {
  alert(event.originalEvent.touches.length);
});

...or you can tell jQuery to copy that property over by doing this once at the beginning of your script:

jQuery.event.props.push("touches");

...whereupon your first example should start working.


Side note: If you're not using jQuery Touch, you might look at it. My guess is that in addition to the other things it does, it adds the touches property as shown above (but that's just a guess).

like image 115
T.J. Crowder Avatar answered Oct 03 '22 14:10

T.J. Crowder