Detect a mobile device in jQuery

Overview

Mobile detection drives alternate layouts or redirects. Pure user-agent sniffing is fragile; combine with viewport width and touch capability.

jQuery Mobile historically used UA; modern sites prefer CSS media queries.

Implementation

Check width: $(window).width() < 768. Touch: 'ontouchstart' in window. UA regex as fallback only. Use matchMedia('(max-width:767px)') with change listeners.

Serve one responsive site instead of m.example.com when possible.

When implementing guidance from Detect a mobile device in jQuery, start in a controlled environment that mirrors production versions of operating systems, runtimes, and network policies. Capture a baseline before changes: export configs, snapshot VMs, or tag releases in source control so rollback stays straightforward if behavior regresses.

Document prerequisites, expected outcomes, and verification steps in a short runbook. Automated checks—smoke tests, health endpoints, or query validations—catch regressions early when platforms receive patches. Security belongs in every workflow: apply least privilege, rotate secrets, and review audit logs after deployment.

If results differ across machines, compare environment variables, permission models, time zones, and regional settings. Intermittent issues often trace to caching layers, stale DNS, or duplicated services bound to the same port.

Example

function isMobile() {
  return window.matchMedia('(max-width: 767px)').matches;
}
$(window).on('resize', function() {
  $('body').toggleClass('is-mobile', isMobile());
});

Tips

  • Prefer feature detection over UA.
  • Test iOS Safari and Chrome Android.
  • Avoid blocking desktop on tablets.
  • Server-side detection duplicates client logic.
  • Re-verify after reboots, certificate renewals, or failover exercises.
  • Align monitoring and alerts with the failure modes described in this guide.
  • Keep vendor documentation links handy for breaking changes between versions.
  • Pair automation with a manual spot check during initial production rollout.