Home > Software design >  How to detect mobile devices with TouchEvent but differentiate touch screen PCs as well by using jav
How to detect mobile devices with TouchEvent but differentiate touch screen PCs as well by using jav

Time:09-03

I know that there are lots of similar questions.

Currently, I use the below code to detect touch screen devices and I mark them as mobile devices.

    function isMobile() {
    try {
        document.createEvent("TouchEvent");
        console.log("mobile");
        return true;
    }
    catch (e) {
        console.log("pc");
        return false;
    }
}

It works good on mobile devices but what about touch screen PCs that also have a keyboard and mouse? How can I differentiate them?

Since I don't have a touch screen PC I am not able to test and solve this issue.

I want to determine if it is a mobile device such as a mobile phone or tablet basically devices that have no mouse and keyboard or it is a PC that has a keyboard and mouse.

CodePudding user response:

If your goal is just to detect if the user is on mobile, using TouchEvent is not the best way.

This StackOverflow Answer details how to detect if a user is on mobile using JS.

CodePudding user response:

I want to determine if it is a mobile device such as a mobile phone or tablet basically devices that have no mouse and keyboard or it is a PC that has a keyboard and mouse.

You can check if a device has a mouse pointer using the method presented by this answer:

const hasCursor = window.matchMedia('(pointer:fine)').matches

As far as I know, this should only be false for devices with no pointer, so laptops with both a touchscreen and a touchpad will not match this and this should be all you need.

Detecting if a keyboard is present is harder, in part because most mobile phones/tablets have support for an external keyboard that can be used. You probably won't need this method as the first way should cover all cases, but you can use a workaround to detect if a keyboard is present by listening for the first keyup event:

let hasKeyboard = false
document.addEventListener("keyup", () => {
  hasKeyboard = true
}, { once: true })

However this is pretty hacky as if a keyboard user never uses their keyboard, they will show up as not having one. Only use this if you need to, otherwise just use the first method.

  • Related