I\'m developing a webapp (not a website with pages of interesting text) with a very different interface for touch (your finger hides the screen when you click) and mouse (re
It's only possible to detect if a browser is touch capable. There is no way to know if it actually has a touch screen or a mouse connected.
One can prioritize the use though by listening to touch event instead of mouse event if touch capability is detected.
To detect touch capability cross-browser:
function hasTouch() {
return (('ontouchstart' in window) || // html5 browsers
(navigator.maxTouchPoints > 0) || // future IE
(navigator.msMaxTouchPoints > 0)); // current IE10
}
Then one can use this to check:
if (!hasTouch()) alert('Sorry, need touch!);
or to choose which event to listen to, either:
var eventName = hasTouch() ? 'touchend' : 'click';
someElement.addEventListener(eventName , handlerFunction, false);
or use separate approaches for touch vs. non-touch:
if (hasTouch() === true) {
someElement.addEventListener('touchend' , touchHandler, false);
} else {
someElement.addEventListener('click' , mouseHandler, false);
}
function touchHandler(e) {
/// stop event somehow
e.stopPropagation();
e.preventDefault();
window.event.cancelBubble = true;
// ...
return false; // :-)
}
function mouseHandler(e) {
// sorry, touch only - or - do something useful and non-restrictive for user
}
For mouse one can only detect if the mouse is being used, not if it exists or not. One can setup a global flag to indicate that mouse was detected by usage (similar to an existing answer, but simplified a bit):
var hasMouse = false;
window.onmousemove = function() {
hasMouse = true;
}
(one cannot include mouseup or mousedown as these event can also be triggered by touch)
Browsers restricts access to low-level system APIs which is needed to be able to detect features such as hardware capabilities of the system it's being used on.
There is the possibility to perhaps write a plugin/extension to access these but via JavaScript and DOM such detection is limited for this purpose and one would have to write a plugin specific for the various OS platforms.
So in conclusion: such detection can only be estimated by a "good guess".