Detect mobile devices and screen size with JavaScript

Detect mobile devices and screen size with JavaScript

Sometimes a script should behave differently on small screens: a menu that opens on tap, a slider with fewer items, a heavy animation that is skipped on phones. The tempting way is to check the user agent string for “Mobile”, and it is the least reliable one: user agents change, tablets claim to be desktops, and desktop browsers in a narrow window are not detected at all. Checking what really matters, the viewport width or the input method, works better.

Problem: A script should switch to a mobile behaviour at the same breakpoint as the CSS, and react when the window is resized or the phone is rotated.

Solution: Use window.matchMedia() with the same media query as the CSS and listen to its change event. Check touch support with pointer media queries or navigator.maxTouchPoints, and use ResizeObserver when the size of one element matters, not the window.

The viewport, like in CSS

var mobile = window.matchMedia( '(max-width: 767px)' );

function applyLayout( query ) {
    if ( query.matches ) {
        document.body.classList.add( 'is-mobile' );
    } else {
        document.body.classList.remove( 'is-mobile' );
    }
}

applyLayout( mobile );                          // on load
mobile.addEventListener( 'change', applyLayout ); // on resize or rotation

Using the same query string as the stylesheet keeps JavaScript and CSS in sync: when the CSS switches to the mobile layout, the script does too. Safari before 14 supports only the older mobile.addListener( applyLayout ); call it as a fallback if you need those versions.

Touch and mouse

The screen size says nothing about the input. A large tablet is touch-only, a small laptop window uses a mouse:

var coarsePointer = window.matchMedia( '(pointer: coarse)' ).matches; // finger as the main input
var canHover      = window.matchMedia( '(hover: hover)' ).matches;    // a mouse or touchpad
var hasTouch      = navigator.maxTouchPoints > 0;                     // touch is available at all

Use them for decisions about interaction: open a submenu on hover only when (hover: hover) matches, otherwise on tap.

The size of one element

When a component sits in a sidebar on desktop and full width on mobile, its own width matters more than the window’s:

var box = document.querySelector( '.ha-product-slider' );

if ( box && 'ResizeObserver' in window ) {
    new ResizeObserver( function ( entries ) {
        entries.forEach( function ( entry ) {
            var width = entry.contentRect.width;
            entry.target.classList.toggle( 'is-narrow', width < 480 );
        } );
    } ).observe( box );
}

Server-side detection

WordPress has wp_is_mobile(), which checks the user agent in PHP. Use it with care: with page caching, the first visitor decides what all others get, so a mobile version cached for a desktop visitor is common. For layout, CSS media queries and the JavaScript above are the reliable tools; wp_is_mobile() is fine only for things that are not cached, such as admin screens.

NOTE: Do not hide important features behind a device check. A form, the navigation or a checkout button must work everywhere; device detection should only change how things look or how they are operated, never whether they are available.