What is the best way to detect a mobile device
Checking for a mobile device in a web app is something that you need to do often. In most cases developers use agent detection. But User Agent detection is not a recommended technique for modern web apps. There is a JavaScript API built-in for detecting media. The JavaScript window.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string. You can use this method to detect a mobile device based on the CSS media query.
<script>
$(document).ready(function(){
let isMobileDevice = window.matchMedia("only screen and (max-width: 760px)").matches;
if(isMobileDevice){
// The viewport is less than 768 pixels wide
//Conditional script here
} else{
//The viewport is greater than 700 pixels wide
alert("This is not a mobile device.");
}
});
</script>
You can use above script to do show/hide elements depending on the screen size.

Use Agent Detection (Not Recommended)
Detecting mobile device using user agent isn't the best way to check if a user is using a mobile device since user agent strings can be spoofed easily. However, this method is still an easy way to check what device is being used by the user. To get the user agent string, you can use the navigator.userAgent property.
var isMobileDevice = false; //initiate as false
// device detection
if( /AndroidwebOSiPhoneiPadiPodBlackBerryIEMobileOpera Mini/i.test(navigator.userAgent) ) {
//Conditional script here
}
It is important to note that the value of the userAgent can be easily changed. For eg: when you use bots to scrape a website, you can pass a completely different user agent value to hide your identity. It will make it difficult to detect the actual device type .
Related Topics
- JavaScript Popup Boxes
- Opening a new window in JavaScript
- How to Create Drop-Down Lists in JavaScript
- How do I include a JavaScript file in another JavaScript file?
- Print the content of a Div using JavaScript/jQuery
- How to get the current URL using JavaScript ?
- How to validate an email address in JavaScript
- JavaScript Array Iteration
- How to Remove a Specific Item from an Array in JavaScript
- What is JavaScript closures?
- How To Remove a Property from a JavaScript Object
- How to get selected value from Dropdown list in JavaScript
- How do I get the current date in JavaScript?
- How to Open URL in New Tab | JavaScript
- How to delay/wait/Sleep in code execution | JavaScript
- How to round to at most 2 decimal places | JavaScript
- How to convert string to boolean | JavaScript
- How to check undefined in JavaScript?
- How To Copy to Clipboard | JavaScript
- How to encode a URL using JavaScript?
- How to force Input field to enter numbers only | JavaScript
- How to create multiline string in JavaScript
- How to Check for an Empty String in JavaScript?