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
}