Brend8c
Brend8c

Reputation: 649

How detecting if the browser has "touch capabilities"?

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

Upvotes: 1

Views: 4603

Answers (1)

A Haworth
A Haworth

Reputation: 36467

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.

Upvotes: 3

Related Questions