Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What's the best way to detect a 'touch screen' device using JavaScript?
The best way to detect a touch screen device is to check whether touch events are supported in the browser's document model. This approach tests for the presence of touch event properties.
Basic Touch Detection
The most reliable method is to check for the ontouchstart property in the document element:
<script>
function checkTouchDevice() {
return 'ontouchstart' in document.documentElement;
}
// Test the function
console.log("Touch device:", checkTouchDevice());
// Display result on page
document.body.innerHTML = "<h3>Touch Device: " + checkTouchDevice() + "</h3>";
</script>
Enhanced Touch Detection Method
For better compatibility across different browsers and devices, you can use multiple checks:
<script>
function isTouchDevice() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
// Test and display results
let touchSupported = isTouchDevice();
let deviceType = touchSupported ? "Touch Device" : "Non-Touch Device";
document.body.innerHTML = `
<h3>Detection Results</h3>
<p>Touch Supported: ${touchSupported}</p>
<p>Device Type: ${deviceType}</p>
`;
</script>
Practical Usage Example
You can use touch detection to conditionally apply different behaviors:
<script>
function detectAndAdapt() {
const isTouchDevice = 'ontouchstart' in document.documentElement;
if (isTouchDevice) {
// Touch device - larger buttons, touch-friendly UI
document.body.style.fontSize = "18px";
document.body.innerHTML = `
<div style="padding: 20px; background: #e8f5e8;">
<h3>Touch Device Detected</h3>
<button style="padding: 15px 30px; font-size: 16px;">Touch-Friendly Button</button>
</div>
`;
} else {
// Non-touch device - standard UI
document.body.innerHTML = `
<div style="padding: 15px; background: #f0f8ff;">
<h3>Non-Touch Device Detected</h3>
<button style="padding: 8px 16px;">Standard Button</button>
</div>
`;
}
}
detectAndAdapt();
</script>
Detection Methods Comparison
| Method | Browser Support | Accuracy |
|---|---|---|
'ontouchstart' in window |
Excellent | Good |
navigator.maxTouchPoints |
Modern browsers | Very Good |
navigator.msMaxTouchPoints |
IE/Edge legacy | Good for older IE |
Important Considerations
Keep in mind that modern devices can have both touch and mouse capabilities. This detection identifies touch capability, not the current input method being used.
Conclusion
Use 'ontouchstart' in document.documentElement for basic touch detection. For comprehensive coverage, combine multiple detection methods to handle various browsers and hybrid devices effectively.
