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.

detecting mobile device using javascript

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 .