Home > Back-end >  Is it possible to exclusively target touch input devices?
Is it possible to exclusively target touch input devices?

Time:12-17

I made an hover effect that would work well on mouse/keyboard interfaces but not so ideally with touch interfaces. I would like to target touch interface devices with some kind of media query or something that sets the touch input devices away from desktop style devices.

I would have used the screen size media queries but there are tablets whose sizes overlap with those of laptops. Is there a way to target touch interface devices with JavaScript or pure CSS or some other way?

CodePudding user response:

You can do it using pointer media query:

div {
  padding: 8px;
  width: 200px;
  border: 1px solid;
}

@media (pointer:fine) {
  div:hover {
    cursor: pointer;
    background-color: red;
  }
}

@media (pointer:coarse) {
  div:active {
    background-color: green;
  }
}
<div>Hover me on PC</div>

The hover property is defined only for those devices which has mouse(fine cursor);

Or you can apply different property for touch screens using
@media (pointer:coarse)

CodePudding user response:

You can sense if a device is a touch one by looking at some capabilities.

For example, the media query on hover tells you whether the device understands 'proper' hovering.

Here's a simple snippet to demonstrate:

.hov:hover {
  color: black;
}

@media (hover: hover) {
  .hov:hover {
    color: red;
  }
}
<div >Hover over me</div>

However, you may want to think through exactly which capabilities you want to test for, remembering that some devices may have both touch and mouse actions.

  • Related