The HTML ontouchstart event
The HTML ontouchstart attribute runs JavaScript when one or more touch points are placed on the touch surface over the element. It is an inline handler for the touchstart event; in modern code prefer addEventListener('touchstart', …).
Overview
The ontouchstart event attribute runs JavaScript when a touch begins on the element. In JavaScript the event itself is named touchstart — 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 ontouchstart HTML attribute, but the modern, recommended approach is element.addEventListener('touchstart', 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 ontouchstart="handler()">…</element>
element.addEventListener('touchstart', handler);
Best practices
- Prefer
element.addEventListener('touchstart', handler)over the inlineontouchstartattribute — 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 ontouchstart event?
touchstart.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 ontouchstart attribute or addEventListener?
addEventListener('touchstart', …) in JavaScript. The inline ontouchstart attribute works but mixes behavior into the markup and allows only one handler per element.