The HTML ontouchcancel event
The HTML ontouchcancel attribute runs JavaScript when a touch point is disrupted (e.g. an alert appears or too many touches occur). It is an inline handler for the touchcancel event; in modern code prefer addEventListener('touchcancel', …).
Overview
The ontouchcancel event attribute runs JavaScript when a touch is interrupted. In JavaScript the event itself is named touchcancel — drop the on prefix when you call addEventListener.
It is one of the Touch Events. The handler receives a TouchEvent whose touches list describes every active touch point, which is what makes multi-touch gestures possible. For most needs, though, the unified pointer events are now preferred over touch-specific handlers.
You can wire this up with the inline ontouchcancel HTML attribute, but the modern, recommended approach is element.addEventListener('touchcancel', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element ontouchcancel="handler()">…</element>
element.addEventListener('touchcancel', handler);
Best practices
- Prefer
element.addEventListener('touchcancel', handler)over the inlineontouchcancelattribute — it separates behavior from markup and allows multiple handlers. - Prefer the unified pointer events unless you specifically need multi-touch details.
- Iterate
event.touches(orchangedTouches) to handle each touch point. - Call
preventDefault()when you need to stop the browser's default scrolling or zooming.
Frequently asked questions
What is the ontouchcancel event?
touchcancel.Should I use touch events or pointer events?
How do I access the touch points?
event.touches list (or event.changedTouches) from the TouchEvent.Should I use the ontouchcancel attribute or addEventListener?
addEventListener('touchcancel', …) in JavaScript. The inline ontouchcancel attribute works but mixes behavior into the markup and allows only one handler per element.