{

How to check browser is on mobile in javascript?


It is a short tutorial about how to check browser device is mobile or not.

Sometimes Developers need to handle specific code specific to the browser on mobile, In such a case, we need to find out whether the browser device is mobile or desktop with JavaScript.

Javascript provides an inbuilt navigator object to know about client-side browser meta information.

The navigator object has the userAgent property to know about browser information.

console.log(navigator.userAgent);
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"

Check browser running on a mobile device in javascript example

using regular expression we can check mobile browser or not, userAgent string contains mobile device information.

userAgent returns mobile device information like webOS, Android, iPhone, iPad, BlackBerry and Opera Mini

function isBrowserMobile(){
  var isMobile=false;
  if(('ontouchstart' in document.documentElement)&&(/webOS|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
    isMobile=true;
  } else {
   isMobile=false;
  }
return isMobile
}

Modernizr example to check mobile device or not

modernizr is a javascript library to check frontend features support in browsers.

<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>

Here is an example using modernizr library

function isBrowserMobile(){
  var isMobile=false;
  if(Modernizr.touch)&&(/webOS|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
    isMobile=true;
  } else {
   isMobile=false;
  }
return isMobile
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.