This question is an update to this one, but for modern browsers. (Unfortunately the answers here are outdated and/or not in vanilla JavaScript). Essentially I want to perform a simple test to detect if a click
event was triggered by touch or mouse input.
The only answer in the aforementioned question that is foolproof and still works is to use the event.pointerType
property. However, event.pointerType
seems to only be defined in Chrome for the click
event.
While I could use pointer-events (for instance pointerup
), for which event.pointerType
is defined for all browsers, pointerup
behaves differently than click
and is more similar to mouseup
. In other words it does not register only true clicks, but also fires if the pointer was dragged around or started on another element.
For this reason, I would like to get this to work with regular click
events. If anyone knows how I can reliably detect the input method it would be greatly appreciated.
2
Answers
A solution could be, first have a
flag
to check if get touched or not let’s call itisTouched
, thisflag
isfalse
by default, and create an event listener on thetouchstart
event and once it get triggered it will turnisTouched
to betrue
, also create another event listener forclick
and inside it conditionally check ifisTouched
istrue
, then reset theisTouched
to befalse
, if it is withfalse
, then there wasn’t a touch event triggered, so it is just aclick
event.A similar approach to the accepted answer but hiding the implementation by dispatching a
PointerEvent
for those browsers that do not support yetclick
event asPointerEvent
We can create a wrapper function that adds the click listener
and handles the logic for touch devices
And once we have the function we use it like this