Home Web Front-end CSS Tutorial How to detect touch devices using browser media queries

How to detect touch devices using browser media queries

Jan 20, 2025 pm 06:10 PM

This article explores reliable methods for detecting user input devices (touch, mouse, stylus) in web development, moving beyond unreliable techniques like screen size checks or user-agent sniffing. The focus is on leveraging CSS Media Queries, specifically pointer, hover, and any-pointer, for accurate device capability detection. These queries provide precise information about input modalities, leading to more accessible and responsive web applications.

While simpler approaches might seem convenient, they often yield inaccurate results. For instance, a user connecting a mouse to a smartphone invalidates size-based assumptions. CSS Media Queries offer a superior solution, providing precise data based on actual device characteristics.

CSS Media Queries: A Reliable Approach

This article delves into pointer and hover Media Queries, demonstrating their implementation as React hooks.

pointer Media Query

The pointer Media Query determines the presence and precision of a pointing device. It returns one of three values:

  • none: No pointing device available (e.g., voice-controlled devices).
  • coarse: A pointing device is present but lacks precision (e.g., finger on a touchscreen).
  • fine: A highly precise pointing device is available (e.g., mouse).

The window.matchMedia method provides convenient access to Media Query results within code.

useMatchMedia Hook

To avoid code redundancy, a custom useMatchMedia hook is created to retrieve and track Media Query results. This hook utilizes window.matchMedia and adds an event listener to detect changes in the query's match status. A cleanup function ensures the listener is removed when the component unmounts or the query changes.

export const useMatchMedia = (query: string) => {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => setMatches(media.matches);
    media.addEventListener('change', listener);
    return () => media.removeEventListener('change', listener);
  }, [matches, query]);

  return matches;
};
Copy after login
Copy after login

Detecting Primary Pointer Capabilities

The usePrimaryPointerQuery hook determines the primary pointer type. It calls useMatchMedia with queries for none, coarse, and fine pointer types, returning the appropriate value from a Pointers enum.

import { useMatchMedia } from './useMatchMedia.ts';
import { Pointers } from './types.ts';

export const usePrimaryPointerQuery = () => {
  const isNone = useMatchMedia('(pointer: none)');
  const isCoarse = useMatchMedia('(pointer: coarse)');
  const isFine = useMatchMedia('(pointer: fine)');
  if (isNone) {
    return Pointers.none;
  } else if (isCoarse) {
    return Pointers.coarse;
  } else if (isFine) {
    return Pointers.fine;
  }
};
Copy after login
Copy after login

How to detect touch devices using browser media queries

Detecting Additional Pointer Capabilities

While only one primary pointer exists, devices can have secondary pointers (e.g., Bluetooth keyboard, joystick). The any-pointer Media Query checks the precision of any available pointer. The useAnyPointerQuery hook accepts a pointer type and uses useMatchMedia with a dynamically generated query string.

export const useMatchMedia = (query: string) => {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => setMatches(media.matches);
    media.addEventListener('change', listener);
    return () => media.removeEventListener('change', listener);
  }, [matches, query]);

  return matches;
};
Copy after login
Copy after login

How to detect touch devices using browser media queries

Working Demo

A complete demo showcasing the hooks is available:

Advanced Detection: hover and any-hover

hover and any-hover Media Queries further refine detection by checking for hover capabilities. Combining these with pointer queries allows for more precise device identification.

Pointer value Hover value Device
coarse none Modern touch screens
fine none Stylus-based devices
coarse hover Joystick or TV remote
fine hover Mouse

For example, detecting a stylus as the primary input:

import { useMatchMedia } from './useMatchMedia.ts';
import { Pointers } from './types.ts';

export const usePrimaryPointerQuery = () => {
  const isNone = useMatchMedia('(pointer: none)');
  const isCoarse = useMatchMedia('(pointer: coarse)');
  const isFine = useMatchMedia('(pointer: fine)');
  if (isNone) {
    return Pointers.none;
  } else if (isCoarse) {
    return Pointers.coarse;
  } else if (isFine) {
    return Pointers.fine;
  }
};
Copy after login
Copy after login

This approach ensures more robust and accurate detection of user input devices, leading to better user experience and accessibility.

The above is the detailed content of How to detect touch devices using browser media queries. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles