Skip to content

Commit 2885a41

Browse files
authored
Merge pull request #137 from odsantos/fix-event-details
Update folder 2-ui/5/3-event-details
2 parents 1a5852e + 4bcccd1 commit 2885a41

File tree

15 files changed

+390
-22
lines changed

15 files changed

+390
-22
lines changed
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
# Pointer events
2+
3+
Pointer events is a modern way to handle input from a variety of pointing devices, such as a mouse, a pen/stylus, a touchscreen and so on.
4+
5+
## The brief history
6+
7+
Let's make a small overview, so that you understand the general picture and the place of Pointer Events among other event types.
8+
9+
- Long ago, in the past, there existed only mouse events.
10+
11+
Then touch devices appeared. For the old code to work, they also generate mouse events. For instance, tapping generates `mousedown`. But mouse events were not good enough, as touch devices are more powerful in many aspects. For example, it's possible to touch multiple points at once, and mouse events don't have any properties for that.
12+
13+
- So touch events were introduced, such as `touchstart`, `touchend`, `touchmove`, that have touch-specific properties (we don't cover them in details here, because pointer events are event better).
14+
15+
Still, it wasn't enough, as there are many other devices, such as pens, that have their own features. Also, writing a code that listens both touch and mouse events was cumbersome.
16+
17+
- To solve these issues, the new standard Pointer Events was introduced. It provides a single set of events for all kinds of pointing devices.
18+
19+
As of now, [Pointer Events Level 2](https://www.w3.org/TR/pointerevents2/) specification is supported in all major browsers, while the [Pointer Events Level 3](https://w3c.github.io/pointerevents/) is in the works. Unless you code for Internet Explorer 10 or Safari 12 and below, there's no point in using mouse or touch events any more. We can switch to pointer events.
20+
21+
That said, there are important peculiarities, one should know them to use them correctly and avoid extra surprises. We'll pay attention to them in this article.
22+
23+
## Pointer event types
24+
25+
Pointer events are named similar to mouse events:
26+
27+
| Pointer Event | Mouse event |
28+
|---------------|-------------|
29+
| `pointerdown` | `mousedown` |
30+
| `pointerup` | `mouseup` |
31+
| `pointermove` | `mousemove` |
32+
| `pointerover` | `mouseover` |
33+
| `pointerout` | `mouseout` |
34+
| `pointerenter` | `mouseenter` |
35+
| `pointerleave` | `mouseleave` |
36+
| `pointercancel` | - |
37+
| `gotpointercapture` | - |
38+
| `lostpointercapture` | - |
39+
40+
As we can see, for every `mouse<event>`, there's a `pointer<event>` that plays a similar role. Also there are 3 additional pointer events that don't have a corresponding `mouse...` counterpart, we'll soon explain about them.
41+
42+
```smart header="Replacing `mouse<event>` with `pointer<event>` in our code"
43+
We can replace `mouse<event>` events with `pointer<event>` in our code and expect things to continue working fine with mouse.
44+
45+
The support for touch devices will also "magically" improve, but we'll probably need to add `touch-action: none` rule in CSS. See the details below in the section about `pointercancel`.
46+
```
47+
48+
## Pointer event properties
49+
50+
Pointer events have the same properties as mouse events, such as `clientX/Y`, `target` etc, plus some extra:
51+
52+
- `pointerId` - the unique identifier of the pointer causing the event.
53+
54+
Allows to handle multiple pointers, such as a touchscreen with stylus and multi-touch (explained below).
55+
- `pointerType` - the pointing device type, must be a string, one of: "mouse", "pen" or "touch".
56+
57+
We can use this property to react differently on various pointer types.
58+
- `isPrimary` - `true` for the primary pointer (the first finger in multi-touch).
59+
60+
For pointers that measure a contact area and pressure, e.g. a finger on the touchscreen, the additional properties can be useful:
61+
62+
- `width` - the width of of the area where the pointer touches the device. Where unsupported, e.g. for mouse it's always `1`.
63+
- `height` - the height of of the area where the pointer touches the device. Where unsupported, always `1`.
64+
- `pressure` - the pressure of the pointer tip, in range from 0 to 1. For devices that don't support pressure must be either `0.5` (pressed) or `0`.
65+
- `tangentialPressure` - the normalized tangential pressure.
66+
- `tiltX`, `tiltY`, `twist` - pen-specific properties that describe how the pen is positioned relative the surface.
67+
68+
These properties aren't very well supported across devices, so they are rarely used. You can find the details in the [specification](https://w3c.github.io/pointerevents/#pointerevent-interface) if needed.
69+
70+
## Multi-touch
71+
72+
One of the things that mouse events totally don't support is multi-touch: a user can touch them in several places at once at their phone or tablet, perform special gestures.
73+
74+
Pointer Events allow to handle multi-touch with the help of `pointerId` and `isPrimary` properties.
75+
76+
Here's what happens when a user touches a screen at one place, and then puts another finger somewhere else on it:
77+
78+
1. At the first touch:
79+
- `pointerdown` with `isPrimary=true` and some `pointerId`.
80+
2. For the second finger and further touches:
81+
- `pointerdown` with `isPrimary=false` and a different `pointerId` for every finger.
82+
83+
Please note: there `pointerId` is assigned not to the whole device, but for each touching finger. If we use 5 fingers to simultaneously touch the screen, we have 5 `pointerdown` events with respective coordinates and different `pointerId`.
84+
85+
The events associated with the first finger always have `isPrimary=true`.
86+
87+
We can track multiple touching fingers using their `pointerId`. When the user moves move and then detouches a finger, we get `pointermove` and `pointerup` events with the same `pointerId` as we had in `pointerdown`.
88+
89+
```online
90+
Here's the demo that logs `pointerdown` and `pointerup` events:
91+
92+
[iframe src="multitouch" edit height=200]
93+
94+
Please note: you must be using a touchscreen device, such as a phone or a tablet to actually see the difference. For single-touch devices, such as a mouse, there'll be always same `pointerId` with `isPrimary=true`, for all pointer events.
95+
```
96+
97+
## Event: pointercancel
98+
99+
We've mentioned the importance of `touch-action: none` before. Now let's explain why, as skipping this may cause our interfaces to malfunction.
100+
101+
The `pointercancel` event fires when there's an ongoing pointer interaction, and then something happens that causes it to be aborted, so that no more pointer events are generated.
102+
103+
Such causes are:
104+
- The pointer device hardware was disabled.
105+
- The device orientation changed (tablet rotated).
106+
- The browser decided to handle the interaction on its own, considering it a mouse gesture or zoom-and-pan action or something else.
107+
108+
We'll demonstrate `pointercancel` on a practical example to see how it affects us.
109+
110+
Let's say we're impelementing drag'n'drop for a ball, just as in the beginning of the article <info:mouse-drag-and-drop>.
111+
112+
Here are the flow of user actions and corresponding events:
113+
114+
1) The user presses the mouse button on an image, to start dragging
115+
- `pointerdown` event fires
116+
2) Then they start dragging the image
117+
- `pointermove` fires, maybe several times
118+
3) Surprise! The browser has native drag'n'drop support for images, that kicks in and takes over the drag'n'drop process, thus generating `pointercancel` event.
119+
- The browser now handles drag'n'drop of the image on its own. The user may even drag the ball image out of the browser, into their Mail program or a File Manager.
120+
- No more `pointermove` events for us.
121+
122+
So the issue is that the browser "hijacks" the interaction: `pointercancel` fires and no more `pointermove` events are generated.
123+
124+
```online
125+
Here's the demo with pointer events (only `up/down`, `move` and `cancel`) logged in the textarea:
126+
127+
[iframe src="ball" height=240 edit]
128+
```
129+
130+
We'd like to implement our own drag'n'drop, so let's tell the browser not to take it over.
131+
132+
**Prevent default browser actions to avoid `pointercancel`.**
133+
134+
We need to do two things:
135+
136+
1. Prevent native drag'n'drop from happening:
137+
- Can do it by setting `ball.ondragstart = () => false`, just as described in the article <info:mouse-drag-and-drop>.
138+
- That works well for mouse events.
139+
2. For touch devices, there are also touch-related browser actions. We'll have problems with them too.
140+
- We can prevent them by setting `#ball { touch-action: none }` in CSS.
141+
- Then our code will start working on touch devices.
142+
143+
After we do that, the events will work as intended, the browser won't hijack the process and emit no `pointercancel`.
144+
145+
```online
146+
This demo adds these lines:
147+
148+
[iframe src="ball-2" height=240 edit]
149+
150+
As you can see, there's no `pointercancel` any more.
151+
```
152+
153+
Now we can add the code to actually move the ball, and our drag'n'drop will work for mouse devices and touch devices.
154+
155+
## Pointer capturing
156+
157+
Pointer capturing is a special feature of pointer events.
158+
159+
The idea is that we can "bind" all events with a particular `pointerId` to a given element. Then all subsequent events with the same `pointerId` will be retargeted to the same element. That is: the browser sets that element as the target and trigger associated handlers, no matter where it actually happened.
160+
161+
The related methods are:
162+
- `elem.setPointerCapture(pointerId)` - binds the given `pointerId` to `elem`.
163+
- `elem.releasePointerCapture(pointerId)` - unbinds the given `pointerId` from `elem`.
164+
165+
Such binding doesn't hold long. It's automatically removed after `pointerup` or `pointercancel` events, or when the target `elem` is removed from the document.
166+
167+
Now when do we need this?
168+
169+
**Pointer capturing is used to simplify drag'n'drop kind of interactions.**
170+
171+
Let's recall the problem we met while making a custom slider in the article <info:mouse-drag-and-drop>.
172+
173+
1) First, the user presses `pointerdown` on the slider thumb to start dragging it.
174+
2) ...But then, as they move the pointer, it may leave the slider: go below or over it.
175+
176+
But we continue tracking track `pointermove` events and move the thumb until `pointerup`, even though the pointer is not on the slider any more.
177+
178+
[Previously](info:mouse-drag-and-drop), to handle `pointermove` events that happen outside of the slider, we listened for `pointermove` events on the whole `document`.
179+
180+
Pointer capturing provides an alternative solution: we can call `thumb.setPointerCapture(event.pointerId)` in `pointerdown` handler, and then all future pointer events until `pointerup` will be retarteted to `thumb`.
181+
182+
That is: events handlers on `thumb` will be called, and `event.target` will always be `thumb`, even if the user moves their pointer around the whole document. So we can listen at `thumb` for `pointermove`, no matter where it happens.
183+
184+
Here's the essential code:
185+
186+
```js
187+
thumb.onpointerdown = function(event) {
188+
// retarget all pointer events (until pointerup) to me
189+
thumb.setPointerCapture(event.pointerId);
190+
};
191+
192+
thumb.onpointermove = function(event) {
193+
// move the slider: listen at thumb, as all events are retargeted to it
194+
let newLeft = event.clientX - slider.getBoundingClientRect().left;
195+
thumb.style.left = newLeft + 'px';
196+
};
197+
198+
// note: no need to call thumb.releasePointerCapture,
199+
// it happens on pointerup automatically
200+
```
201+
202+
```online
203+
The full demo:
204+
205+
[iframe src="slider" height=100 edit]
206+
```
207+
208+
**As a summary: the code becomes cleaner as we don't need to add/remove handlers on the whole `document` any more. That's what pointer capturing does.**
209+
210+
There are two associated pointer events:
211+
212+
- `gotpointercapture` fires when an element uses `setPointerCapture` to enable capturing.
213+
- `lostpointercapture` fires when the capture is released: either explicitly with `releasePointerCapture` call, or automatically on `pointerup`/`pointercancel`.
214+
215+
## Summary
216+
217+
Pointer events allow to handle mouse, touch and pen events simultaneously.
218+
219+
Pointer events extend mouse events. We can replace `mouse` with `pointer` in event names and expect our code to continue working for mouse, with better support for other device types.
220+
221+
Remember to set `touch-events: none` in CSS for elements that we engage, otherwise the browser hijacks many types of touch interactions and pointer events won't be generated.
222+
223+
Additional abilities of Pointer events are:
224+
225+
- Multi-touch support using `pointerId` and `isPrimary`.
226+
- Device-specific properties, such as `pressure`, `width/height` and others.
227+
- Pointer capturing: we can retarget all pointer events to a specific element until `pointerup`/`pointercancel`.
228+
229+
As of now, pointer events are supported in all major browsers, so we can safely switch to them, if IE10- and Safari 12- are not needed. And even with those browsers, there are polyfills that enable the support of pointer events.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<!doctype html>
2+
<body style="height: 200px">
3+
<style>
4+
#ball {
5+
touch-action: none;
6+
}
7+
</style>
8+
9+
<p>Drag the ball.</p>
10+
11+
<img src="https://js.cx/clipart/ball.svg" style="cursor:pointer" width="40" height="40" id="ball">
12+
13+
<script>
14+
15+
ball.onpointerdown = log;
16+
ball.onpointerup = log;
17+
ball.onpointermove = log;
18+
ball.onpointercancel = log;
19+
20+
ball.ondragstart = () => false;
21+
22+
let lastEventType;
23+
let n = 1;
24+
function log(event) {
25+
if (lastEventType == event.type) {
26+
n++;
27+
text.value = text.value.replace(/.*\n$/, `${event.type} * ${n}\n`);
28+
return;
29+
}
30+
lastEventType = event.type;
31+
n = 1;
32+
text.value += event.type + '\n';
33+
text.scrollTop = 1e9;
34+
}
35+
</script>
36+
37+
<textarea id="text" style="display:block;width:300px;height:100px"></textarea>
38+
</body>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<!doctype html>
2+
<body style="height: 200px">
3+
<p>Drag the ball.</p>
4+
5+
<img src="https://js.cx/clipart/ball.svg" style="cursor:pointer" width="40" height="40" id="ball">
6+
7+
<script>
8+
9+
ball.onpointerdown = log;
10+
ball.onpointerup = log;
11+
ball.onpointermove = log;
12+
ball.onpointercancel = log;
13+
14+
let lastEventType;
15+
let n = 1;
16+
function log(event) {
17+
if (lastEventType == event.type) {
18+
n++;
19+
text.value = text.value.replace(/.*\n$/, `${event.type} * ${n}\n`);
20+
return;
21+
}
22+
lastEventType = event.type;
23+
n = 1;
24+
text.value += event.type + '\n';
25+
text.scrollTop = 1e9;
26+
}
27+
</script>
28+
29+
<textarea id="text" style="display:block;width:300px;height:100px"></textarea>
30+
</body>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<!doctype html>
2+
<body>
3+
<style>
4+
#area {
5+
border: 1px solid black;
6+
width: 90%;
7+
height: 180px;
8+
cursor: pointer;
9+
overflow: scroll;
10+
user-select: none;
11+
}
12+
</style>
13+
14+
<div id="area">
15+
Multi-touch here
16+
</div>
17+
<script>
18+
document.onpointerdown = document.onpointerup = log;
19+
20+
function log(event) {
21+
area.insertAdjacentHTML("beforeend", `
22+
<div>${event.type} isPrimary=${event.isPrimary} pointerId=${event.pointerId}</div>
23+
`)
24+
area.scrollTop = 1e9;
25+
}
26+
</script>
27+
28+
</body>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<!DOCTYPE html>
2+
<link rel="stylesheet" href="style.css">
3+
4+
<div id="slider" class="slider">
5+
<div class="thumb"></div>
6+
</div>
7+
8+
<script>
9+
let thumb = slider.querySelector('.thumb');
10+
let shiftX;
11+
12+
thumb.onpointerdown = function(event) {
13+
event.preventDefault(); // prevent selection start (browser action)
14+
15+
shiftX = event.clientX - thumb.getBoundingClientRect().left;
16+
17+
thumb.setPointerCapture(event.pointerId);
18+
};
19+
20+
thumb.onpointermove = function(event) {
21+
let newLeft = event.clientX - shiftX - slider.getBoundingClientRect().left;
22+
23+
// if the pointer is out of slider => adjust left to be within the bounaries
24+
if (newLeft < 0) {
25+
newLeft = 0;
26+
}
27+
let rightEdge = slider.offsetWidth - thumb.offsetWidth;
28+
if (newLeft > rightEdge) {
29+
newLeft = rightEdge;
30+
}
31+
32+
thumb.style.left = newLeft + 'px';
33+
};
34+
35+
thumb.ondragstart = () => false;
36+
37+
</script>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
.slider {
2+
border-radius: 5px;
3+
background: #E0E0E0;
4+
background: linear-gradient(left top, #E0E0E0, #EEEEEE);
5+
width: 310px;
6+
height: 15px;
7+
margin: 5px;
8+
}
9+
10+
.thumb {
11+
width: 10px;
12+
height: 25px;
13+
border-radius: 3px;
14+
position: relative;
15+
left: 10px;
16+
top: -5px;
17+
background: blue;
18+
cursor: pointer;
19+
}
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)