Distinguish between touch only and mouse-and-touch devices
Alright, my mistake. I tried a different google search approach and that way, i found the answer:
How to detect if a device has mouse support?
In order to summarize, this is the code I am using:
if (window.matchMedia("(any-pointer: coarse)").matches) {
hasTouch = true;
}
if (matchMedia('(pointer:fine)').matches) {
hasMouse = true;
}
This way, you can detect if:
-The device has touch only (hasTouch&&!hasMouse)
-The device has mouse only (!hasTouch&&hasMouse)
-The device has both touch and mouse (hasTouch&&hasMouse)
How detecting if the browser has touch capabilities?
To answer the question exactly as set, if you put this function into your Javascript code you can just run it and set a flag which you can use in your code afterwards if you want to do things differently for a touchscreen.
function isTouchDevice() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
const myFlag = isTouchDevice();
....
// example
if (myFlag) { alert('You can move the object with your finger'); }
else { alert('Use the arrow keys on your keyboard to move the object'); }
But remember a user may use the device as a touchscreen one minute and as a keyboard device the next. You can code for sensing both key and touch events and unless your site absolutely needs the user to use a touch device you can accommodate both methods of input.
Detect click vs. touch in JavaScript
You can use the pointerType
property on PointerEvent
to detect the input type ("mouse"
, "touch"
, or "pen"
):
element.addEventListener('pointerdown', (event) => {
if (event.pointerType === "mouse") {}
if (event.pointerType === "touch") {}
if (event.pointerType === "pen") {}
});
If you want specific events for each type of click, you can create custom events:
const mouse = new Event("mouseclick");
const touch = new Event("touch");
document.addEventListener("pointerdown", ({ pointerType, target }) => {
if (pointerType === "mouse") target.dispatchEvent(mouse);
if (pointerType === "touch") target.dispatchEvent(touch);
});
const someElement = document.querySelector(".box");
someElement.addEventListener("mouseclick", () => {
console.log("Clicked with mouse");
});
someElement.addEventListener("touch", () => {
console.log("Touched with mobile device");
});
someElement.addEventListener("click", () => {
console.log("Clicked by some device (we don't know)");
});
.box {
position: absolute;
inset: 2em;
background: darkred;
padding: 1em;
}
<div class="box">A box with custom events</div>
What's the best way to detect a 'touch screen' device using JavaScript?
Update: Please read blmstr's answer below before pulling a whole feature detection library into your project. Detecting actual touch support is more complex, and Modernizr only covers a basic use case.
Modernizr is a great, lightweight way to do all kinds of feature detection on any site.
It simply adds classes to the html element for each feature.
You can then target those features easily in CSS and JS. For example:
html.touch div {
width: 480px;
}
html.no-touch div {
width: auto;
}
And Javascript (jQuery example):
$('html.touch #popup').hide();
How to detect touch device in 2019?
This is really simple with just one line of code:
const touch = matchMedia('(hover: none)').matches;
- What? matchMedia
?
- This is just a JS API to do CSS @media queries. And it is supported in modern browsers: https://caniuse.com/#feat=matchmedia. Of course, you may use such queries directly in CSS:
@media (hover: none){
/* touch stuff goes here */
}
- Ok, what @media queries may be also useful?
@media (hover: none) and (pointer: coarse) {
/* touchscreens */
}
@media (hover: none) and (pointer: fine) {
/* stylus */
}
@media (hover: hover) and (pointer: coarse) {
/* controllers */
}
@media (hover: hover) and (pointer: fine) {
/* mouse or touchpad */
}
But this will query only the primary input method. If you want to go deeper, you may use any-hover
and any-pointer
to query all input devices.
UPD: hack for old browsers removed, seems like most old browsers does not support hover
and pointer
media queries too. You may use touch event detection and touch-only navigator
properties from another answers
UPD2: In your case, it's preferable to use
const touch = matchMedia('(hover: none), (pointer: coarse)').matches;
javascript detect desktop touch and mouse support
After some research, I have found that the best solution was to use this code:
https://github.com/matthewhudson/device.js
So, the way it works, is by giving the body element class names which represent the device and orientation, and with that I can pretty much guess if the user has a mouse. (class desktop
is applied)
Related Topics
Why Can't I Add Properties to a String Object in JavaScript
How to Efficiently Randomly Select Array Item Without Repeats
How to Enable Cors Nodejs with Express
Controlling Fps with Requestanimationframe
How to Make Exe Files from a Node.Js App
How to Implement Authenticated Routes in React Router 4
How to Turn JavaScript Array into Comma-Separated List
How to Sort an Array of Objects with Jquery or JavaScript
React This.Setstate Is Not a Function
Using Settimeout on Promise Chain
How to Check If the User Can Go Back in Browser History or Not
How to Add Months to a Date in JavaScript
What's the Difference Between & and && in JavaScript
How to Automatically Allow Blocked Content in Ie
Jquery Submit Form and Then Show Results in an Existing Div
How to Get HTML Elements from an Object Tag
Emailing Google Sheet Range (With or Without Formatting) as a HTML Table in a Gmail Message