Skip links

jQuery JavaScript Detect mobile devices

Easy and tested methods to detect mobile devices using jQuery or JavaScript. Pure JavaScript has method to detect mobile device type called navigator.userAgent.

JavaScript Method

window.navigator.userAgent

Execute the following code to detect the mobile device.

if( /Android|webOS|iPhone|iPad|Mac|Macintosh|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  // yes, it's a mobile device
}

// OR use the touch feature
var isMobile = ('ontouchstart' in document.documentElement && /mobi/i.test(navigator.userAgent);

 

jQuery Method

Here we are checking the window size.

if(window.matchMedia("(max-width: 767px)").matches){
  // The viewport is less than 768 pixels wide
  alert("This is a mobile device.");
} else{
  // The viewport is at least 768 pixels wide
  alert("This is a tablet or desktop.");
}

 

Regarding the navigator.userAgent, keep in mind that users of a browser can change the value of this field if they want (UA spoofing).
Browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable.

  • In Firefox, you can change the preference general.useragent.override in about:config. Some Firefox extensions do that; however, this only changes the HTTP header that gets sent, and doesn’t affect browser detection performed by JavaScript code.
  • Microsoft Internet Explorer uses the Windows registry.
  • Opera 6+ allows users to set the browser identification string via a menu.
  • Safari allow users to change the browser user agent string to predefined Internet Explorer or Netscape strings via a menu.

More details from Mozilla Firefox page.