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:
- What Is a Web Worker In JavaScript?
- How To Sort an Array of Strings In JavaScript?
- ECMAScript vs JavaScript
- What Is Strict Mode In JavaScript?
- Arrow Functions In JavaScript
- Difference Between Node.js and AngularJS With Example
- Difference Between == And === In JavaScript
- What Is JSON In JavaScript
- How To Go Back To Previous Page In JavaScript?
- How To Close The Current Tab In A Browser Window Using JavaScript?
- How To Convert Input Text To Uppercase While Typing Using JavaScript?
- How To Show A Confirmation Message Before Delete In JavaScript?
- How To Detect Browser or Tab Closing In JavaScript?
- How To Get Hash Value From URL Using JavaScript?
- How To Get The Name, Size, And Type Of A File In JavaScript?
- Run JavaScript From The Command Line