How to detect a mobile device in jQuery?
We can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query. This is the best and easiest way to detect mobile devices.
Syntax:
window.matchMedia();
Example-1: Program run on desktop.
<!DOCTYPE html> <html lang="en"> <head> <title> jQuery Detect Mobile Device </title> </head> <body> <script> 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."); } </script> </body> </html> |
chevron_right
filter_none
Output:

Example-2: Program run on mobile device.
<!DOCTYPE html> <html lang="en"> <head> <title> jQuery Detect Mobile Device </title> </head> <body> <script> 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."); } </script> </body> </html> |
chevron_right
filter_none
Output:

Supported Browsers:
- Google Chrome
- Mozilla Firefox
- Opera
- Edge
- Safari
Recommended Posts:
- How to detect the user's device using jQuery ?
- How to detect the device is an Android device using JavaScript ?
- Detect a device is iOS or not using JavaScript
- How to detect touch screen device using JavaScript?
- How to detect escape key press using jQuery?
- JQuery | Detect a textbox content is changed or not
- How to get the height of device screen in JavaScript ?
- How to get the width of device screen in JavaScript ?
- JavaScript | Detecting a mobile browser
- How to disable zoom on a mobile web page using CSS?
- Mobile Search Engine Optimization (SEO)
- How to place the image above the slider in mobile view in bootstrap?
- Introduction to Xamarin | A Software for Mobile App Development and App Creation
- How to target desktop, tablet and mobile using Media Query ?
- How to detect browser or tab closing in JavaScript ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



