DEV Community

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

Collapse
 
linehammer profile image
linehammer

You can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query.

if (window.matchMedia("(max-width: 767px)").matches)
{
// The viewport is less than 768 pixels wide
document.write("This is a mobile device.");
}

You may also use navigator.userAgentData.mobile .

const isMobile = navigator.userAgentData.mobile;

Another approach would be a responsive media query. You could presume that a mobile phone has a screen size greater than x and less than y. For example:

@media only screen and (min-width: 320px) and (max-width: 600px) {}

net-informations.com/js/iq/default...

Collapse
 
kouba profile image
Martin Kouba

Unfortunately navigator.userAgentData.mobile appears to be not widely supported yet

caniuse.com/?search=userAgentData
caniuse.com/?search=mobile

Collapse
 
timhuang profile image
Timothy Huang

Thanks for sharing!