/ hoversizedetect

hoversizedetect.js

Detect a device's hover capability and pointer precision via window.matchMedia.
Lightweight, vanilla JavaScript.

javascript matchmedia hover-detection responsive esm

Installation

npm install hoversizedetect

Setup

import HoverSizeDetect from 'hoversizedetect';

const myInstance = new HoverSizeDetect({
  breakpoint: 992,  // in px
  debug: true,      // show info in console
});

myInstance.init();   // initialize

Options

OptionTypeDefaultDescription
breakpoint Number 992 Matches against min-width in px. If set to 768, returns is >= 768px.
debug Boolean false If true, collected info is logged to the console.

matchMedia Queries

QueryResult
(pointer: coarse) touchMobile
(pointer: fine), (pointer: none) and (any-hover: hover) desktop
(pointer: fine) and (any-pointer: coarse) touchDesktop *

* e.g. a touch screen laptop with hover ability but no pointer device connected.

Body Classes

Body classes are set automatically depending on screen size and hover ability.

Mode 1
.is-above-eq-{bp}
.has-hover
>= breakpoint, has hover
Mode 2
.is-below-{bp}
.no-hover
< breakpoint, no hover
Mode 3
.is-above-eq-{bp}
.no-hover
>= breakpoint, no hover
Mode 4
.is-below-{bp}
.has-hover
< breakpoint, has hover

Collected Data

Access collected data via .getInfo() — returns an object.

const info = myInstance.getInfo();

// Example: desktop at 1920×1080 with mouse connected
{
  query:   "(pointer: fine), (pointer: none) and (any-hover: hover)",
  type:    "desktop",
  size:    { width: 1920, height: 1080 },
  info:    "is >= 992, has hover",
  mode:    1,
  hasHover: true
}