1

I saw the solution to my question. But I do not understand how to use this..
Please explain: how does this function work?
Do I need to pass events to it?
Or do I need to hang it on the click of a button?
Show an example how I can use

function isTouchDevice() {
  return (('ontouchstart' in window) ||
     (navigator.maxTouchPoints > 0) ||
     (navigator.msMaxTouchPoints > 0));
}

Main article

Brendan8c
  • 369
  • 2
  • 11
  • 1
    Why do you need to check if device has touch screen? What if device has touch screen, but user is using mouse - there are such laptops/tablets? – Justinas Mar 15 '21 at 08:09
  • Does this answer your question? [What's the best way to detect a 'touch screen' device using JavaScript?](https://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript) – Masood Mar 15 '21 at 08:10
  • @Justinas Determine whether it is a mobile phone or not.. – Brendan8c Mar 15 '21 at 09:19
  • 1
    @Артем Not all touch screens are mobile phones (and not all mobile phones have a touch screen for that matter) – Jamiec Mar 15 '21 at 09:25
  • 1
    It is better to detect device capabilities and not distinguish between mobile and non mobile devices. Just make universal design/code. Detecting touch screen will only tell you that there are touch capabilities. Detecting small viewport size will only tell you current viewport. You theoretically can parse user agent, but it can be faked (I do this for some sites). – Mr. Hedgehog Mar 15 '21 at 09:26
  • You'd be better off with https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser – Jamiec Mar 15 '21 at 09:26

1 Answers1

3

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.

A Haworth
  • 30,908
  • 4
  • 11
  • 14