Search code examples
csstouchmedia-queries

Media query to detect if device is touchscreen


What is the safest way, using media queries, to make something happen when not on a touchscreen device? If there is no way, do you suggest using a JavaScript solution such as !window.Touch or Modernizr?


Solution

  • Nowadays, CSS Media queries can be used to define style for devices with specific interactive features and it's widely supported as well.

    hover for example can be used to test whether the user's primary input mechanism can hover over elements (which would not be true in touch-enabled devices without emulating)

    @media (hover: none) {
      a {
        background: yellow;
      }
    }
    

    Other interactive tests are: pointer, any-pointer, hover, and any-hover

    Previous answer

    I would suggest using modernizr and using its media query features.

    if (Modernizr.touch){
       // bind to touchstart, touchmove, etc. and watch `event.streamId`
    } else {
       // bind to normal click, mousemove, etc.
    }
    

    However, using CSS, there are pseudo class like, for example in Firefox. You can use :-moz-system-metric(touch-enabled). But these features are not available for every browser.

    For Apple devices, you can simply use:

    if (TouchEvent) {
       //...
    }
    

    Especially for iPad:

    if (Touch) {
        // ...
    }
    

    But, these do not work on Android.

    Modernizr gives feature detection abilities, and detecting features is a good way to code, rather than coding on basis of browsers.

    Styling Touch Elements

    Modernizer adds classes to the HTML tag for this exact purpose. In this case, touch and no-touch so you can style your touch related aspects by prefixing your selectors with .touch. e.g. .touch .your-container. Credits: Ben Swinburne