How to check browser is on mobile in javascript?


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

Some times Developers need to handle specific code specific to browser in mobile, In such case we need to find out whether browser device is mobile or desktop with JavaScript.

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

navigator object has 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 mobile device in javascript example

using regular expression we ca 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 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.