- The gotpointercapture event is triggered when you assign the capture of a pointer with setPointerCapture and lets you know when the item starts receiving all events from that pointer.
- The Pointer Events API unifies mouse, touch, and stylus, reducing duplicate code and improving performance compared to separate handlers.
- Pointer capture, combined with pointercancel and touch-action, is key to smooth dragging and avoiding inconsistent states.
- Managing pointers by pointerId and releasing the capture with releasePointerCapture avoids conflicts in multi-touch interactions.
For years, websites have had to deal with a major mess: mouse events on one hand, touch events on another, and to top it all off, stylus or pen events. Each device brought its own events, and developers ended up maintaining duplicate code for mousedown, touchstart, and so on. The Pointer Events API arrives to bring order and offer a common interface that abstracts all these devices. With Pointer Events, you program only once, and the browser handles the differences , reducing redundancy and simplifying maintenance.
Within that ecosystem, the event gotpointercapture It's a fundamental component when you need an element to continue receiving events even if the pointer goes out of bounds. It fires the moment an element captures a pointer. setPointerCapture()Throughout this article we will see how it works, what properties it brings with it and how to integrate it with the rest of the pointer events to set up drags, drawings and controls that work equally well with mouse, finger or stylus.
What is the gotpointercapture event and what is it used for?
About the event gotpointercapture It is launched when an element receives the capture of a pointer using setPointerCapture()At that moment, the element becomes the destination of all subsequent events of that specific pointer, even if the cursor or finger moves out of its box. It's a sign that the capture has worked. and that you can start managing the trail without worrying about losing track.
There are two ways to listen to it. The first is addEventListener('gotpointercapture', (event) => { ... })The second is to assign a function to the property ongotpointercapture of the element. Be careful, because this second option replaces any previous driver that you would have used with the same property. The object you receive is a PointerEvent, which he inherits from Event and brings all the information about the punitive involved.
A very simple example: you select a paragraph, you listen gotpointercapture to find out that the capture has been activated and, in pointerdown, you call setPointerCapture(event.pointerId)Thus, when the user clicks, you will see a notification in the console that the paragraph has been captured. The natural pairing for this event is lostpointercapturewhich is triggered when the capture is released or lost. Controlling both prevents you from becoming zombie-like.
const parrafo = document.querySelector('p'); parrafo.addEventListener('gotpointercapture', () => { console.log('¡Me han capturado!'); }); parrafo.addEventListener('pointerdown', (evento) => { parrafo.setPointerCapture(evento.pointerId); });
If you prefer the handler property, the code looks similar: parrafo.ongotpointercapture = () => { ... }. Yes, Don't mix both methods without knowing what you're doing.because direct assignment can overwrite previous listeners. This event is part of the Pointer Events supplementary events group, along with pointerover, pointerout, pointerenter y pointerleave.
The Pointer Events API as a unified solution
Pointer Events was created to solve the puzzle of handling mice, touchscreens, and styluses separately. Its approach is a single, device-agnostic interface which represents the state changes of any pointer. Among its advantages are code consolidation and improved performance due to the reduced need for so many preventDefault() defensive capabilities and access to rich metadata such as pressure, angle, and contact geometry. Furthermore, It is prepared for future input technologies without you having to rewrite your application.
There are four main events: pointerdown when the pointer becomes active, pointerup when released, pointermove when coordinates change and pointercancel when the browser decides that that pointer will no longer generate any more events (for example, due to a change in orientation or a system interruption). Then there are the supplementary ones: pointerover, pointerout, pointerenter, pointerleave, gotpointercapture y lostpointercapture. Each one has its own nuanceThose who wear enter y leave They don't bubble, while over y ... Yes, they do.
Key properties of a PointerEvent
When you handle a pointer event, you receive a lot of useful information. For example, clientX y clientY They give you the position relative to the viewport, while pageX y pageY They give it regarding the document. pointerId uniquely identifies each pointer, pointerType It tells you if it is mouse, pen o touch, and isPrimary indicates if it is the main pointer. This data is the basis for distinguishing devices and managing multiple contacts at once..
The pressure is exposed in pressureA value between 0.0 and 1.0. On mice, it's usually set to 0.5; on touchscreens, it varies depending on the contact surface; and on styluses, it allows for force-sensitive drawing. You also have width y height for the contact geometry, tiltX y tiltY for pencil tilt, twist for rotation and button/buttons to find out which button has been pressed. With this metadata you can create creative experiences, such as strokes that change thickness or color depending on the pressure.
First steps with unified handlers
A good starting point is a drawing canvas. With Pointer Events, the same code works for mouse, finger, and stylus. You listen pointerdown to activate drawing mode, pointermove to draw lines and pointerup o pointercancel to deactivate it. You don't need to check the device type Unless you want to fine-tune the behavior. The key is to use the event coordinates and maintain a boolean state indicating whether you're drawing.
const lienzo = document.getElementById('lienzo'); const ctx = lienzo.getContext('2d'); let dibujando = false; let ultimaX = 0; let ultimaY = 0; lienzo.addEventListener('pointerdown', (e) => { dibujando = true; [ultimaX, ultimaY] = [e.offsetX, e.offsetY]; }); lienzo.addEventListener('pointermove', (e) => { if (!dibujando) return; ctx.beginPath(); ctx.moveTo(ultimaX, ultimaY); ctx.lineTo(e.offsetX, e.offsetY); ctx.stroke(); [ultimaX, ultimaY] = [e.offsetX, e.offsetY]; }); lienzo.addEventListener('pointerup', () => { dibujando = false; }); lienzo.addEventListener('pointercancel', () => { dibujando = false; });
Notice that the same handler serves all devicesHowever, it is advisable to clean the state both in pointerup as in pointercancelBecause the browser may cancel the interaction for reasons beyond your control. If you only hear pointerupYou risk the canvas remaining in drawing mode forever.
Managing multiple pointers simultaneously
Pointer Events comes with built-in multi-touch support. The cleanest way to manage it is to use a Map indexed by pointerIdEvery time a pointerdown, you save the coordinates and the pointer type; in pointermove You update the data; and in pointerup o pointercancel You delete the entry. This way you maintain the independent status of each contact. and you avoid a global boolean messing things up when there are two fingers on the screen.
const punterosActivos = new Map(); elemento.addEventListener('pointerdown', (e) => { punterosActivos.set(e.pointerId, { x: e.clientX, y: e.clientY, tipo: e.pointerType }); }); elemento.addEventListener('pointermove', (e) => { if (!punterosActivos.has(e.pointerId)) return; punterosActivos.set(e.pointerId, { x: e.clientX, y: e.clientY, tipo: e.pointerType }); if (punterosActivos.size === 2 && e.pointerType === 'touch') { const [p1, p2] = Array.from(punterosActivos.values()); const distancia = Math.hypot(p1.x - p2.x, p1.y - p2.y); console.log('Distancia entre dedos:', distancia); } }); elemento.addEventListener('pointerup', (e) => { punterosActivos.delete(e.pointerId); }); elemento.addEventListener('pointercancel', (e) => { punterosActivos.delete(e.pointerId); });
With two touch pointers you can calculate the Euclidean distance and set up a pinch-to-zoom. The key is not to delete all the pointers when you get up: removes only the one that corresponds to that pointerIdIf you use a simple isPressed = falseThe remaining fingers are left orphaned and the interaction breaks down.
Pointer capture: absolute control of dragging
Pointer capture is what allows an element to continue receiving events even if the pointer moves out of its area. When you call setPointerCapture(event.pointerId) within pointerdown, the element becomes the destination of all the pointermove, pointerup and other events of that pointer. That's where it comes into play gotpointercapture, which notifies you that the capture has been established. To release it, use releasePointerCapture(event.pointerId) or let the browser release it when finished.
Imagine a slider with a draggable thumbnail. In pointerdown captures the pointer, in pointermove You calculate the new position relative to the lane and limit the movement to the extremes, and in pointerup You release the capture. About the event lostpointercapture It helps you clean the state If the capture is lost unexpectedly, this prevents the thumbnail from getting stuck to the cursor after an interrupted drag.
const slider = document.getElementById('slider'); const thumb = slider.querySelector('.thumb'); let arrastrando = false; thumb.addEventListener('pointerdown', (e) => { arrastrando = true; thumb.setPointerCapture(e.pointerId); e.preventDefault(); }); thumb.addEventListener('pointermove', (e) => { if (!arrastrando) return; const rect = slider.getBoundingClientRect(); const anchoThumb = thumb.offsetWidth; let nuevoLeft = e.clientX - rect.left - anchoThumb / 2; nuevoLeft = Math.max(0, Math.min(nuevoLeft, rect.width - anchoThumb)); thumb.style.left = nuevoLeft + 'px'; }); thumb.addEventListener('pointerup', (e) => { arrastrando = false; thumb.releasePointerCapture(e.pointerId); }); thumb.addEventListener('lostpointercapture', () => { arrastrando = false; });
For a complete draggable component, encapsulate the logic in a class. Configure touch-action: none y user-select: none to prevent text selection and scrolling while dragging. Save the pointerId current to avoid mixing pointers and uses setPointerCapture() at the pointerdown. Don't forget to release the capture and clean up CSS classes in pointerupIf the device supports it, you can create a minimal vibration with navigator.vibrate(1) to provide tactile feedback.
class ElementoArrastrable { constructor(elemento) { this.elemento = elemento; this.arrastrando = false; this.pointerId = null; this.inicioX = 0; this.inicioY = 0; this.offsetX = 0; this.offsetY = 0; this.init(); } init() { this.elemento.style.touchAction = 'none'; this.elemento.style.userSelect = 'none'; this.elemento.addEventListener('pointerdown', this.onDown.bind(this)); this.elemento.addEventListener('pointermove', this.onMove.bind(this)); this.elemento.addEventListener('pointerup', this.onUp.bind(this)); this.elemento.addEventListener('pointercancel', this.onUp.bind(this)); } onDown(e) { if (this.arrastrando) return; this.arrastrando = true; this.pointerId = e.pointerId; this.elemento.setPointerCapture(e.pointerId); const rect = this.elemento.getBoundingClientRect(); this.inicioX = e.clientX - rect.left; this.inicioY = e.clientY - rect.top; this.offsetX = rect.left; this.offsetY = rect.top; this.elemento.classList.add('arrastrando'); } onMove(e) { if (!this.arrastrando || e.pointerId !== this.pointerId) return; const nuevaX = e.clientX - this.inicioX; const nuevaY = e.clientY - this.inicioY; this.elemento.style.position = 'fixed'; this.elemento.style.left = nuevaX + 'px'; this.elemento.style.top = nuevaY + 'px'; if (e.pointerType === 'touch' && 'vibrate' in navigator) navigator.vibrate(1); } onUp(e) { if (e.pointerId !== this.pointerId) return; this.arrastrando = false; this.elemento.releasePointerCapture(e.pointerId); this.elemento.classList.remove('arrastrando'); this.pointerId = null; } }
Pressure drawing and input type detection
Styluses and some touchscreens allow you to draw with pressure. You can map e.pressure to the thickness of the line or the intensity of the color. On mice, the pressure is usually 0.5, so the stroke comes out at a medium thickness; with a pencil, the more pressure you apply, the thicker and warmer the stroke becomes. If the pointer is of type penYou can also read tiltX, tiltY y twist to simulate realistic brushes.
lienzo.addEventListener('pointermove', (e) => { if (e.buttons === 0) return; const presion = e.pressure || 0.5; const grosor = presion * 20; const intensidad = Math.floor(presion * 255); ctx.strokeStyle = `rgb(${intensidad}, 0, ${255 - intensidad})`; ctx.lineWidth = grosor; ctx.lineTo(e.offsetX, e.offsetY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(e.offsetX, e.offsetY); if (e.pointerType === 'pen') { console.log({ presion, tiltX: e.tiltX, tiltY: e.tiltY }); } });
You can also adapt the behavior according to pointerType. For mouse You might want to display tooltips or hover states; for touch, expand the hit area and avoid the 300ms delay with preventDefault(); and for pento distinguish between a soft touch and a hard press. A single handler with a switch about pointerType It allows you to give each device specific treatment without duplicating all the logic.
Avoid default behaviors and optimize with CSS
On touchscreens, the browser has its own ideas about scrolling, zooming, and text selection. You can stop them with e.preventDefault()However, this can negatively impact performance because it forces the browser to wait for your JavaScript to execute. The recommended alternative is the CSS property touch-actionwhich is processed earlier and declaratively. For example, touch-action: none disables all gestures on a game canvas, while touch-action: pan-y It allows vertical scrolling but leaves custom horizontal gestures free.
#juego { touch-action: none; } #carrusel { touch-action: pan-y; } #zoom { touch-action: pinch-zoom; }
If you need to use preventDefault()Do it only when the event is of type touch and make sure you're not going to break the scroll. Don't mix handlers pointerdown y touchstart for the same actionBecause on touch devices both events are triggered, and you'll end up executing the logic twice. Choose one event model, preferably Pointer Events, and stick with it.
Another important detail: the event pointercancel it is not optionalThe browser triggers it when interaction is interrupted, for example, if the device orientation changes or a system interface appears. If you only clear the state in pointerupYou might end up with a hanging drag. Always add a handler. pointercancel that does the same cleaning as pointerup.
Good practices and common mistakes
One of the most common mistakes is not releasing pointer capture. If you call setPointerCapture() and you never execute releasePointerCapture()The element continues to receive events from that pointer forever, and other interface elements stop receiving interactions. Always pair capture and releaseand lean on lostpointercapture to clean just in case.
It's also common to mix pointer events with mouse or touch events. On a touch device, the same gesture can trigger pointerdown, mousedown y touchstartIf you listen to all three, Your handler will run multiple times And you'll notice strange behavior. Stick with Pointer Events and forget about the others for new logic.
To prevent accidental text selections during a drag, apply user-select: none y -webkit-user-select: none to the draggable element. The property touch-action: none It also helps prevent the browser from trying to scroll while you're dragging. And if you're managing multiple pointers, use one. Map by pointerId instead of a global boolean; thus, a raised finger does not cancel the state of the others.
In terms of compatibility, Pointer Events works on modern browsers: Chrome 55+, Firefox 59+, Safari 13+ and Edge 12+. You can detect the support with 'PointerEvent' in windowIf you need to support older browsers, use a polyfill like PEP (Pointer Events Polyfill) or maintain a fallback with mouse and touch events. However, be sure not to load the fallback if the browser already supports the native API.
About the event gotpointercapture And the rest of the Pointer Events API gives you very fine control over mouse, finger, and stylus without having to write three versions of the same code. Pointer capture lets you drag without losing your train of thought. pointercancel It saves you from inconsistent states and touch-action It keeps performance in check. It manages pointers by pointerIdIt releases the capture when needed and leverages metadata such as pressure or tilt to provide added quality. With these parts you can assemble interfaces that work equally well on any device and you get rid of the puzzle of separate events.
FAQ
When exactly does the gotpointercapture event fire?
It is triggered the instant an element receives a pointer capture using setPointerCapture. From that moment on, the element receives events from that pointer even if it goes outside its boundaries.
How can I listen for gotpointercapture on an element?
You can use addEventListener with the name gotpointercapture or assign a function to the element's ongotpointercapture property. The second option overrides any previously assigned handler for that same property.
What is the difference between gotpointercapture and lostpointercapture?
`gotpointercapture` indicates that a capture has been activated, while `lostpointercapture` indicates that the capture has been released or lost. These two events allow you to control the capture's lifecycle.
Why isn't setPointerCapture working for me, and why am I not receiving gotpointercapture?
This can happen if you call `setPointerCapture` with a `pointerId` that doesn't correspond to an active pointer, or if the element isn't in the DOM. It's also a good idea to check that the `pointerdown` event is firing and that the browser supports pointer events.
Do I need to call releasePointerCapture after using the capture?
Yes, it's recommended to release the capture when the interaction ends so that other elements can receive events from that pointer. You can do this in `pointerup` or rely on the browser to release it, but controlling it yourself prevents unexpected states.
How does pointer capture affect pointermove events outside the element?
With capture active, the element continues to receive pointermove even if the pointer is outside its box. This is precisely what allows dragging without losing track when the cursor or finger moves out of the area.
Can gotpointercapture be used with multiple pointers at once?
Each pointer has its own pointerId and its own capture, so you can manage multiple pointers at once by saving the state in a Map. The gotpointercapture event will fire for each individual capture you make.
What do I do if my browser doesn't support Pointer Events?
You can detect support using 'PointerEvent' in window, and if it's not available, use a polyfill like PEP or maintain a fallback with mouse and touch events. The important thing is not to mix both models in the same logic.
Table of Contents
- 1 What is the gotpointercapture event and what is it used for?
- 2 The Pointer Events API as a unified solution
- 3 Key properties of a PointerEvent
- 4 First steps with unified handlers
- 5 Managing multiple pointers simultaneously
- 6 Pointer capture: absolute control of dragging
- 7 Pressure drawing and input type detection
- 8 Avoid default behaviors and optimize with CSS
- 9 Good practices and common mistakes
- 10 FAQ




