Touch events

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Touch events

Try using the Spinning Pacman on your phone. You won’t be able to get any Pacman to follow your finger around.

Why? Because we built Spinning Pacman by listening to mouse events! We did not support touch events yet.

Detecting touch

First, you need to open the console from a device that supports touch input. You can try:

  1. Using your computer if there is a touchscreen. (Most Windows computers supports touch).
  2. Using your phone. Here are instructions for iPhone and Android.

Touch events

There are 4 touch events:

  1. touchstart
  2. touchmove
  3. touchend
  4. touchcancel

touchstart is like mousedown. It triggers when you touch the screen with a finger. Each finger triggers a new touchstart event.

touchmove triggers when you move your finger on a screen.

touchend is similar to mouseup. It triggers when a finger leaves the screen. If you remove two fingers on the screen, touchend will trigger two times.

touchcancel triggers when a touch event gets disrupted.

I tested and found out that:

  • iPhone supports up to 5 touch points. If you add a 6th touch point, you’ll trigger touchcancel.
  • Windows 10 (on Surface Laptop 3) supports 10 touch points. But it doesn’t trigger touchcancel even when I have 15 fingers on screen.

Note: Navigator.maxTouchPoints can be used to determine the maximum number of simultaneous touch points.

Touch and Mouse

It’s easy to support Touch and Mouse if you want to trigger a click event. Touch devices will trigger mousedown,mouseup, and click automatically if you press the screen with the intention to click.

Events triggered by touching with the intention to click.

If you want to support other gestures like touchmove, you have two options:

  1. Add the Touch and Mouse events separately.
  2. Use Pointer events (See next lesson).

Touch event properties

There are three touch properties:

  1. touches: list of Touch objects that are in contact with the surface.
  2. targetTouches: touches that start from the same target element.
  3. changedTouches: touches that have changed since the last Touch event.

Touch objects

Each Touch object has the following properties:

  1. target: The element that was touched initially.
  2. identifier: A unique identifier for this touch object.
  3. pageX & pageY: Position of touch relative to the document
  4. clientX & clientY: Position of touch relative to the viewport
  5. screenX & screenY: Position of touch relative to screen

You can also find the information like force, radiusX, radiusY, and rotationAngle in each touch object. We won’t cover them since we won’t use them in this course.