١٠ سبتمبر ٢٠٢٠

Pointer events

Pointer events are a modern way to handle input from a variety of pointing devices, such as a mouse, a pen/stylus, a touchscreen, and so on.

The brief history

Let’s make a small overview, so that you understand the general picture and the place of Pointer Events among other event types.

  • Long ago, in the past, there were only mouse events.

    Then touch devices became widespread, phones and tablets in particular. For the existing scripts to work, they generated (and still generate) mouse events. For instance, tapping a touchscreen generates mousedown. So touch devices worked well with web pages.

    But touch devices have more capabilities than a mouse. For example, it’s possible to touch multiple points at once (“multi-touch”). Although, mouse events don’t have necessary properties to handle such multi-touches.

  • So touch events were introduced, such as touchstart, touchend, touchmove, that have touch-specific properties (we don’t cover them in detail here, because pointer events are even better).

    Still, it wasn’t enough, as there are many other devices, such as pens, that have their own features. Also, writing code that listens for both touch and mouse events was cumbersome.

  • To solve these issues, the new standard Pointer Events was introduced. It provides a single set of events for all kinds of pointing devices.

As of now, Pointer Events Level 2 specification is supported in all major browsers, while the newer Pointer Events Level 3 is in the works and is mostly compartible with Pointer Events level 2.

Unless you develop for old browsers, such as Internet Explorer 10, or for Safari 12 or below, there’s no point in using mouse or touch events any more – we can switch to pointer events.

Then your code will work well with both touch and mouse devices.

That said, there are some important peculiarities that one should know in order to use Pointer Events correctly and avoid surprises. We’ll make note of them in this article.

Pointer event types

Pointer events are named similarly to mouse events:

Pointer event Similar mouse event
pointerdown mousedown
pointerup mouseup
pointermove mousemove
pointerover mouseover
pointerout mouseout
pointerenter mouseenter
pointerleave mouseleave
pointercancel -
gotpointercapture -
lostpointercapture -

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 explain them soon.

Replacing mouse<event> with pointer<event> in our code

We can replace mouse<event> events with