detect mobile device using javascript

Detect Mobile Device in JavaScript

JavaScript is a powerful programming language used by web developers. Sometimes developers need to detect if the user’s device is mobile or laptop in order to personalize browsing experience. This can be easily accomplished using plain JavaScript. Once you detect mobile device using JavaScript, you can place mobile-ready code in appropriate code blocks that are executed only when the web page is loaded in a mobile device. For example, you can use it to direct visitors to your mobile website.


Detect Mobile Device in JavaScript

There are several ways to detect mobile device in JavaScript.

1. With UserAgent

One of the simplest ways to do this is by detecting the value of user agent. Depending on the user’s device, web browsers automatically set the value of user agent property. You can use its value to determine the kind of device that is being used. In the if condition we are using a regular expression within /…/ and our regular expression consists of a set of strings separated by ‘|’ to imply OR operator.

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // some code..
}

In the above code, we read the value of navigator.userAgent and check if it is one of Android, webOS, etc. which indicate that the user is using a mobile device to view your page.


2. With window.matchMedia

You can also use window.matchMedia() to detect mobile device using CSS media queries. Here is an example. In the following code, the if condition evaluates to true when it is run on mobile device but returns false when it is run on tablets, laptops, and devices with bigger screens.

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

In the above code, we have used 768px as the maximum width of mobile device. This should capture most mobile devices. You can always customize it as per your requirement.

In this article, we have learnt how to detect mobile device in JavaScript. You can use this code to detect mobile device and redirect users to your mobile site. You can also use it to customize your website, depending on whether it is loaded in mobile or other devices.

Also read:

How to Detect Click Outside Element in JavaScript
How to Capitalize First Letter in JavaScript
Python Run Shell Command & Get Output
How to Generate All Permutations of Python List
How to Sort List of Dictionaries By Value in Python

Leave a Reply

Your email address will not be published. Required fields are marked *