DEV Community

Discussion on: A simple way to detect if browser is on a mobile device with Javascript

Collapse
 
linehammer profile image
linehammer

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.

$(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.");
}
});

You can use above script to do show/hide elements depending on the screen size.

net-informations.com/js/progs/mobi...