Can I ascertain if something is a touch device

… 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?

1 Like

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:

4 Likes

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 …

1 Like

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)

5 Likes

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

1 Like