Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createTouch vs ontouchstart - best way to detect touchscreen devices?

Currently, for detecting touchscreen devices I use this in my javascript:

if ('createTouch' in document) {
// do touchscreen-specific stuff 
}

I see that many developers use ontouchstart, like this:

if ('ontouchstart' in document) {
// do touchscreen-specific stuff 
}

What is the difference between createTouch and ontouchstart? Which one is the safest to use? Are there some other simple, reliable alternatives to these two?

like image 619
Malasorte Avatar asked Feb 24 '15 06:02

Malasorte


2 Answers

touchstart event is fired when a touch point is placed on the touch surface([MDN][1])

createTouch method creates and returns a new Touch object.([MDN][2])

The better way from my point of view is detecting existance of event in window than only create it.

Also your statement check only for existing of touch events in window object, not touch screens, like windows phones, so probably you would like to check pointer-events too.

P.S.: Look at Modernizr library which have "touch" detection and much more.

like image 65
Smile0ff Avatar answered Nov 13 '22 08:11

Smile0ff


ontouchstart is event based trigger. It will be invoked when user does some action. More info at ontouchstart event. Hence, it is more efficient for performing user based action.

While createtouch will be invoked, not matter if user did some action or not. Somebody please correct me, if I'm wrong. :)

like image 2
Abhishek Avatar answered Nov 13 '22 07:11

Abhishek