How to Detect Mobile Device With Javascript (Simple Examples)

Welcome to a tutorial on how to detect mobile devices with Javascript. So you have some features on your website that you want to offer to mobile users only? Or maybe you want to hide some “desktop only” features from the mobile users?

One of the easiest ways to detect mobile devices in Javascript is to check if the word “mobile” exists in the HTTP user agent – if (navigator.userAgent.toLowerCase().match(/mobile/i)) { IS MOBILE DEVICE }

That covers the basics, but let us walk through a few more examples in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Mobile Detection Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

JAVASCRIPT MOBILE DETECTION

All right, let us now get into the examples of mobile detection in Javascript.

 

1) SIMPLE DETECTION WITH USER AGENT

1-detect.html
window.addEventListener("load", () => {
  // (A) CHECK FOR MOBILE
  var isMobile = navigator.userAgent.toLowerCase().match(/mobile/i);
 
  // (B) DO SOMETHING...
  if (isMobile) { console.log("Is mobile device"); }
  else { console.log("Not mobile device"); }
});

As in the introduction above, the easiest way to detect mobile devices is to look for the word “mobile” in the user agent. For you guys who do not know what the user-agent is, it is simply a small piece of header data that the browser sends to the server – It contains various information on the browser name, operating systems, versions, and platform.

 

2) BETTER USER AGENT DETECTION

2-detect-more.html
window.addEventListener("load", () => {
  // (A) BREAK USER AGENT DOWN
  var isMobile = navigator.userAgent.toLowerCase().match(/mobile/i),
      isTablet = navigator.userAgent.toLowerCase().match(/tablet/i),
      isAndroid = navigator.userAgent.toLowerCase().match(/android/i),
      isiPhone = navigator.userAgent.toLowerCase().match(/iphone/i),
      isiPad = navigator.userAgent.toLowerCase().match(/ipad/i);
 
  // (B) DETECTED DEVICE TYPE
  console.log("Mobile", isMobile);
  console.log("Tablet", isTablet);
  console.log("Android", isAndroid);
  console.log("iPhone", isiPhone);
  console.log("iPad", isiPad);
});

Yes, we can do more “detailed checks” on the user-agent – It is even possible to determine if the user is Android/iOS/Windows/Mac.

 

 

3) USING A DETECTION LIBRARY

3-mobile-detect.html
<!-- (A) LOAD THE LIBRARY -->
<!-- https://github.com/hgoebl/mobile-detect.js -->
<!-- https://hgoebl.github.io/mobile-detect.js/doc/MobileDetect.html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobile-detect/1.4.5/mobile-detect.min.js"></script>
 
<!-- (B) DEVICE DETECTION -->
<script>
window.addEventListener("load", () => {
  var md = new MobileDetect(window.navigator.userAgent);
  console.log( md.mobile() ); // null if not mobile device
  console.log( md.phone() ); // null if not smartphone
  console.log( md.tablet() ); // null if not tablet
  console.log( md.userAgent() ); // Browser used. Chrome, Firefox, Dolfin, etc...
  console.log( md.os() ); // Android, iOS, Windwows, OSX, or Linux
  console.log( md.version('Webkit') ); // Webkit version
  console.log( md.versionStr('Build') ); // Build
});
</script>

Finally, if you really need to go down into the “micro-management level” of mobile detection – I will recommend you use a library instead. There are quite a few that you can use, but here is one of the more popular options, Mobile Detect LibraryDocumentation.

 

 

USEFUL BITS & LINKS

That’s all for this project, and here is a small section on some extras and links that may be useful to you.

 

LIMITATIONS & ALTERNATIVE

Please take note that the user agent is not 100% accurate, users can easily change or hide the user agent using browser extensions. The better way is to do proper responsive design and use feature detection. For example, if your app requires GPS, check if the Geolocation API is supported in the user’s browser. A feature detection library I recommend is Modernizr.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

How To Detect Mobile Devices In Javascript (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this short guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “How to Detect Mobile Device With Javascript (Simple Examples)”

  1. another good way to check for the device type is using window.matchMedia like this:

    // All touch devices (landscape, portrait)
    var isTouchDevice = window.matchMedia(“(pointer:coarse)”).matches

    // Mobile devices (landscape, portrait)
    var isMobileDevice = window.matchMedia(“(pointer:coarse) and (max-width: 575.98px)”).matches

    // Tablet (landscape+portrait)
    var isTabletLP = window.matchMedia(“(pointer:coarse) and (min-width: 576px)”).matches

    // Tablet (landscape)
    var isTabletLandscape = window.matchMedia(“(pointer:coarse) and (min-width: 576px) and (orientation: landscape)”).matches

    // Tablet (portrait)
    var isTabletPortrait = window.matchMedia(“(pointer:coarse) and (min-width: 576px) and (orientation: portrait)”).matches

    1. Sorry, but this is far from a “good way”… It simply assumes all touchscreens with certain resolutions are tablets or mobiles. Which is obviously not the case.

Leave a Comment

Your email address will not be published.