There are several ways to detect if a user is on a mobile device using JavaScript, some of the most popular ways are:

Using the ‘navigator.userAgent property:’ This property contains a string that represents the user agent of the browser. You can use regular expressions to check for the presence of mobile device-specific keywords in the user agent string. For example:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
   // Code for mobile devices
}

Using the ‘screen.width’ and ‘screen.height’ properties: You can check the screen width and height of the device to determine if it’s a mobile device or not. For example:

if(screen.width <= 480 || screen.height <= 480) {
   // Code for mobile devices
}

Using the ‘window.innerWidth’ and ‘window.innerHeight’ properties: Similarly to the above method, you can also use the inner width and height of the window to check if the device is a mobile device or not. For example:

if(window.innerWidth <= 480 || window.innerHeight <= 480) {
   // Code for mobile devices
}

Using the ‘matchMedia’ method: you can use the ‘matchMedia’ method to check if the device is a mobile device or not. For example:

if(matchMedia("only screen and (max-width: 480px)").matches) {
   // Code for mobile devices
}

It’s important to note that these methods are not always reliable and may not work for all devices or browsers. Therefore, it’s a good practice to test your code on multiple devices and browsers to ensure that it works as expected.

Also Read:

Categorized in: