Sometimes you might be looking for some features to include into your web-app that should only be available to devices with a touch screen. You may need this detection while introducing newer smarter controls for touch screen users in the game app or a GPS and navigation application. While there are many JavaScript libraries such as Modernizer, jQuery, etc, that are explicitly designed to do such kind of tasks.
It is noted that the device supports touch events doesn’t necessarily mean that it is exclusively a touch screen device. Many of the high-end ultrabooks are touch enabled. So for better user experience, you should consider a few more attributes alongside checking for a touch screen device.
To perform this check, targeting all possible browsers out there, we will be using following three properties;
- ontouchstart: An event handler that handles event triggered after touching a DOM element.
- maxTouchPoints: A read-only property of a Navigator interface returns the maximum number of simultaneous touch contact points that the device supports.
- msMaxTouchPoints: Same as above, just with vendor prefix “ms” to target browsers IE 10 and below.
Syntax:
javascript
function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 ); } |
Example: This example displays an image if it detect touch screen device otherwise image will not display.
html
<!DOCTYPE html> < html > < head > < title > Detect touch screen device using JavaScript </ title > </ head > < body > < p > Detect touch screen device using JavaScript </ p > < p > If touch screen detected then display an image otherwise image will not display </ p > < div id="GFG"></ div > < script type="text/javascript"> function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 ); } var src = if( is_touch_enabled() ) { var img = "< img src=" + src + " height = '100' />";; } else { var img = ""; } document.getElementById('GFG').innerHTML = img; </ script > </ body > </ html > |
Output:
- Output on non-touch screen:
- Output on touch screen:
Example 2: In this example, a <div> is draggable only if the device is touch-enabled.
html
<!DOCTYPE html> < html > < head > < title > Detect touch screen device using JavaScript </ title > < link href= rel="stylesheet"> </ script > < script src= jquery.ui.touch-punch.min.js"> </ script > < style > #draggable { width: 150px; height: 50px; text-align: center; } </ style > < script > function is_touch_enabled() { return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ) || ( navigator.msMaxTouchPoints > 0 ); } if( is_touch_enabled() ) { $(function() { $( "#draggable" ).draggable(); }); } </ script > </ head > < body > < div id="draggable" class="ui-widget-content"> < p >Draggable Elements!</ p > </ div > </ body > </ html > |
Output:
- Output on non-touch screen:
- Output on touch screen: