Search code examples
javascripthtmlcssmedia-queriestouch

Is it possible to exclusively target touch input devices?


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?


Solution

  • 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)