July 9, 2012

Touchscreen media-queries

Question by JJ56

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

Thanks in advance!

Answer by Starx

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 psedo class like, for example in firefox. You can use :-moz-system-metric(touch-enabled). But these features are not available for every browswers.

For Apple devices, you can simple use:

if(window.TouchEvent) {
   //.....
}

Specially for Ipad

if(window.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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!