How to detect if the device is touch in pure javascript?

Asked

Viewed 107 times

1

I need to add touch events only if necessary. If the device is not touch, I will only add mouse events. For this, I need to check and have a return. It is important, if possible, that the code is in pure js, because I want to learn js.

  • I think it is duplicated: https://answall.com/questions/363967/howto check a-aus%C3%aancia-de-um-device-pointing-na-p%C3%a1gina-em-desktops

1 answer

1


You can check if the event touch that you want exists in the global object window.

For example, if you are going to use the event ontouchstart, you can do so:

if ('ontouchstart' in window) {
  // Adicione o seu listener...
}

In my case, as I am on a device that does not support this event, the code block would not run.

  • Nice. It helped. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.