4

How to detect a mobile device in Javascript

 1 year ago
source link: https://www.laravelcode.com/post/how-to-detect-a-mobile-device-in-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to detect a mobile device in Javascript

  396 views

  10 months ago

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. 

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK