Check if a device is a touchscreen

Published July 2, 2019
.* :☆゚

Sometimes it’s useful to know if the device a user is visiting on is a touchscreen or not. This is because touchscreens don’t generally render things like hover states.

In my case, I sometimes make dropdown navigation menus that rely on css-based hovers to display the sub menus.

With devices such as the iPad Pro, menus will usually still render as the desktop version because the screen size is so big. If you rely on css-based hovers though you need to ensure a user can tap to open the menu instead of hover if their device is a touchscreen.

Enter this conditional:

if ( document.body.clientWidth <= 1024 || "ontouchstart" in document.documentElement ) {
	// your code here
}