How to detect a mobile device in Javascript

In today time, everyone wants to make responsive website. Some websites owner also wants to redirect mobile devices user to mobile website.

In this tutorial article, we will discuss few ways you can find device is mobile or computer. There are many ways you can detact device with Javascript.

Javascript provides simple way to get userAgent. By this way, you can check the current device.

var isMobile = false;
if( /Android|webOS|iPhone|iPad|Mac|Macintosh|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    isMobile = true;

The other one way is to find whether ontouchstart is available then it is likely to be a mobile device.

var isMobile = ('ontouchstart' in document.documentElement);

The third option is to check device width. Mostly device width less than 760px are mobile. If you only want to check screen width and serve user according to device width, then this is the perfect method. There is a JavaScript API built-in to detect media size.

var isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;


if(screen.width <= 760) {
    isMobile = true;

Though, there is no any 100% accurate method to find exact details, still the above methods are useful for it. If you have any method other than these, please let us know in below comment section.