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?
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.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With