Can I ascertain if something is a touch device

AI-generated summary

The discussion is about determining if a device is a touch device, not just mobile, in Javascript. merefield asks if it’s possible without using CSS. david suggests using CSS media queries, such as hover, pointer, any-hover, and any-pointer, which can be run from JS using window.matchMedia. merefield explains their use case, where they want to show excerpts over an image on hover, but not on touch devices. david mentions the capabilities service, which has properties that might help, but notes that this logic has caused issues in the past and may be replaced with a CSS media query-based strategy. merefield finds the capabilities service interesting, but not well-known.

… in Javascript?

And I don’t mean mobile, I mean any device, e.g. touch device like a tablet, where hover doesn’t make sense.

Or am I forced to use CSS?

One tricky thing to consider is laptops with touch screens. In that case, the primary interaction tends to be via a mouse… even though the device technically has a touch screen. That has caused us some headaches recently with reactions :sweat_smile:

But to answer your specific question: I think CSS media queries are the way to go. We have hover, pointer, any-hover and any-pointer.

And then you can run those CSS media queries from JS using window.matchMedia like this:

yeah, good point and nice suggestion.

I was trying to use theme settings to determine when some excerpts should appear over an image which is normally only shown on hover

In my case, options would be:

  • always on
  • only on touch devices (because hover is not really available on tablets/phones)
  • only on hover (normal case)

Over recognising touch devices might not be a disaster in this instance :sweat_smile:

I was just hoping there was some direct Site attribute I’d missed, but I’ll look into your suggestion. A mini CSS refactor with some concatClasses looks likely though …

The capabilities service has some properties which might help. e.g:

Although worth noting: this logic is what caused us headaches recently. I imagine we’ll replace it with the css-media-query-based strategy in the not too distant future. (when this was written, I don’t think those media queries were widely available)

oooh that’s a stealthy service … not seen that much in source! :male_detective: