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"

How to Check browser version on a mobile device using 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 the 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
}