Categories
JavaScript Answers

How to detect that the browser has no mouse and is touch-only with JavaScript?

Spread the love

Sometimes, we want to detect that the browser has no mouse and is touch-only with JavaScript.

In this article, we’ll look at how to detect that the browser has no mouse and is touch-only with JavaScript.

How to detect that the browser has no mouse and is touch-only with JavaScript?

To detect that the browser has no mouse and is touch-only with JavaScript, we can detect if the device supports hovering with window.matchMedia.

For instance, we write

if (window.matchMedia("(any-hover: none)").matches) {
  // ...
}

to call window.matchMedia with "(any-hover: none)" to check if the device supports hovering over content with the mouse.

And we use matches to return whether this is true or false.

Conclusion

To detect that the browser has no mouse and is touch-only with JavaScript, we can detect if the device supports hovering with window.matchMedia.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *