Detecting a “Touch Screen” Device Using Modernizr [Quicktip]

I’m amazed at how the mobile phone evolved over the years. Today, mobile phones are touch-enabled, can be used to surf sites like on a desktop PC, and carry a lot of handy apps to help you be more productive. When we build responsive websites that aim for mobile devices, sometimes we want to include specific and extra capabilities for users to make use of its multi-touch capability.

But before that, we need to first identify if the device has support for touch interaction, and it is easy to do so with Modernizr.

Feature Detection with Modernizr

At the Modernizr download page, ensure that the Touch Event option is selected.

You can then add this Modernizr.touch in your script. Here is a simple example to tell whether the device supports for touch.

if (Modernizr.touch) { 
	alert('Touch Screen');
} else { 
	alert('No Touch Screen');

It’s a basic JavaScript that will show the following popup.

Furthermore, you can also use this method to load touchSwipe, a jQuery plugin for touch gestures, conditionally. You can do so with the Modernizr.load method as follows.

	test: Modernizr.touch,
	yep : 'touchSwipe.js',

The above code will test for touch capability. If it returns yep, meaning the browser/device is capable, it will load the touchSwipe.js.

Final Thought

As more and more people acquire touchscreen devices, it is a good idea to allow your site to be touch-enabled, where possible. This will leave a good impression for your visitors, and it is helpful with user engagement. Being able to detect whether the device is touch-enabled is the first step.